Выполнение 3 лабораторной работы
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Npgsql;
|
||||
using StackExchange.Redis;
|
||||
using Testcontainers.PostgreSql;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
// Один одноразовый контейнер PostgreSQL и один Valkey на весь тестовый прогон. Приложение поднимается в процессе теста
|
||||
// и применяет миграции к пустой БД, как при настоящем старте. Нужен только запущенный Docker.
|
||||
// Настройки передаются через UseSetting (а не переменные окружения), поэтому тест может поднять второй экземпляр
|
||||
// приложения с другими настройками: fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2")).
|
||||
public sealed class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
|
||||
{
|
||||
public const string PostgresImage = "postgres:17@sha256:b8faeff7712663c2773a190181e1246e37e364b887611c04658c28b44e2408fe";
|
||||
private const string ValkeyImage = "valkey/valkey:8.1@sha256:640c5e62cea04b6d6f2084232651d0cc70362d31f4f805e7be94dbed6855e8f2";
|
||||
|
||||
private readonly PostgreSqlContainer _db = new PostgreSqlBuilder().WithImage(PostgresImage).Build();
|
||||
|
||||
private readonly IContainer _cache = new ContainerBuilder()
|
||||
.WithImage(ValkeyImage)
|
||||
.WithPortBinding(6379, true)
|
||||
.WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Ready to accept connections"))
|
||||
.Build();
|
||||
|
||||
private string _connectionFile = string.Empty;
|
||||
|
||||
public string ConnectionString => _db.GetConnectionString();
|
||||
public string CacheConnection => $"{_cache.Hostname}:{_cache.GetMappedPublicPort(6379)}";
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await Task.WhenAll(_db.StartAsync(), _cache.StartAsync());
|
||||
_connectionFile = WriteConnectionFile(_db.GetConnectionString());
|
||||
}
|
||||
|
||||
async Task IAsyncLifetime.DisposeAsync()
|
||||
{
|
||||
await _db.DisposeAsync();
|
||||
await _cache.DisposeAsync();
|
||||
File.Delete(_connectionFile);
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseSetting("DATABASE_URL_FILE", _connectionFile);
|
||||
builder.UseSetting("CACHE_CONNECTION", CacheConnection);
|
||||
builder.UseSetting("DIAGNOSTIC_HEADERS", "true");
|
||||
// В Compose схему применяет отдельный контейнер (--migrate); тестовый процесс мигрирует пустую БД сам.
|
||||
builder.UseSetting("MIGRATE_ON_START", "true");
|
||||
builder.UseSetting("SHUTDOWN_DRAIN_SECONDS", "0");
|
||||
}
|
||||
|
||||
public static string WriteConnectionFile(string connectionString)
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"messenger-test-{Guid.NewGuid():N}.conn");
|
||||
File.WriteAllText(path, connectionString);
|
||||
return path;
|
||||
}
|
||||
|
||||
// Прямой доступ к БД для проверок, которые нельзя выразить через API (например, состояние таблицы sessions).
|
||||
public async Task<NpgsqlConnection> OpenConnectionAsync()
|
||||
{
|
||||
var connection = new NpgsqlConnection(ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
return connection;
|
||||
}
|
||||
|
||||
public async Task<T?> ScalarAsync<T>(string sql, params (string Name, object Value)[] parameters)
|
||||
{
|
||||
await using var db = await OpenConnectionAsync();
|
||||
await using var command = new NpgsqlCommand(sql, db);
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
|
||||
var result = await command.ExecuteScalarAsync();
|
||||
return result is null or DBNull ? default : (T)result;
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync(string sql)
|
||||
{
|
||||
await using var db = await OpenConnectionAsync();
|
||||
await using var command = new NpgsqlCommand(sql, db);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
// Полная очистка содержимого кэша (эквивалент FLUSHALL / перезапуска Valkey без persistence).
|
||||
public async Task FlushCacheAsync()
|
||||
{
|
||||
using var connection = await ConnectionMultiplexer.ConnectAsync(
|
||||
new ConfigurationOptions { EndPoints = { CacheConnection }, AllowAdmin = true });
|
||||
await connection.GetServer(connection.GetEndPoints()[0]).FlushAllDatabasesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition("api")]
|
||||
public sealed class ApiCollection : ICollectionFixture<ApiFixture>;
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
internal sealed record TestUser(Guid Id, string Username, string Password, string Token);
|
||||
|
||||
internal static class ApiHelpers
|
||||
{
|
||||
public const string DefaultPassword = "correct horse battery staple";
|
||||
|
||||
public static StringContent Json(string raw) =>
|
||||
new(raw, Encoding.UTF8, "application/json");
|
||||
|
||||
// user != null — запрос с Bearer-токеном этого пользователя.
|
||||
public static HttpRequestMessage Request(HttpMethod method, string url, TestUser? user = null, HttpContent? content = null)
|
||||
{
|
||||
var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
if (user is not null)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public static async Task<JsonElement> ReadJsonAsync(HttpResponseMessage response)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
return JsonDocument.Parse(body).RootElement.Clone();
|
||||
}
|
||||
|
||||
public static async Task<string> ErrorCodeAsync(HttpResponseMessage response)
|
||||
{
|
||||
var json = await ReadJsonAsync(response);
|
||||
return json.GetProperty("error").GetProperty("code").GetString()!;
|
||||
}
|
||||
|
||||
public static string BasicHeader(string username, string password) =>
|
||||
"Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
|
||||
|
||||
public static async Task<HttpResponseMessage> LoginAsync(HttpClient client, string username, string password)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(username, password));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
// Регистрирует пользователя и входит: возвращает его с рабочим Bearer-токеном.
|
||||
public static async Task<TestUser> CreateUserAsync(HttpClient client, string? username = null)
|
||||
{
|
||||
username ??= "u" + Guid.NewGuid().ToString("N")[..12];
|
||||
var response = await client.PostAsJsonAsync("/api/v1/users",
|
||||
new { username, display_name = "Тест", password = DefaultPassword });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
|
||||
var login = await LoginAsync(client, username, DefaultPassword);
|
||||
Assert.Equal(HttpStatusCode.Created, login.StatusCode);
|
||||
var token = (await ReadJsonAsync(login)).GetProperty("token").GetString()!;
|
||||
return new TestUser(id, username, DefaultPassword, token);
|
||||
}
|
||||
|
||||
public static async Task<Guid> CreateChatAsync(HttpClient client, TestUser owner, params TestUser[] others)
|
||||
{
|
||||
var members = others.Append(owner).Select(u => u.Id).ToArray();
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", owner,
|
||||
JsonContent.Create(new { title = "Чат", member_ids = members }));
|
||||
var response = await client.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
}
|
||||
|
||||
// key == null — новый уникальный Idempotency-Key (каждое сообщение независимо); иначе повтор с заданным ключом.
|
||||
public static async Task<HttpResponseMessage> SendMessageAsync(
|
||||
HttpClient client, TestUser sender, Guid chatId, string text, string? key = null)
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender,
|
||||
JsonContent.Create(new { text }));
|
||||
request.Headers.Add("Idempotency-Key", key ?? Guid.NewGuid().ToString("N"));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
public static async Task<List<Guid>> ReadAllMessagesAsync(HttpClient client, Guid chatId, TestUser user, int limit)
|
||||
{
|
||||
string? cursor = null;
|
||||
var received = new List<Guid>();
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, user);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid()));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
}
|
||||
while (cursor is not null);
|
||||
return received;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class ApiTests(ApiFixture fixture)
|
||||
{
|
||||
private HttpClient NewClient() => fixture.CreateClient();
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithMalformedJson_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", Json("{bad"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithoutBody_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", null);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithDuplicateUsername_ReturnsConflict()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{user.Username}}","display_name":"Другой","password":"{{DefaultPassword}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
Assert.Equal("conflict", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("short")]
|
||||
[InlineData("12345678901")] // 11 символов
|
||||
public async Task CreateUser_WithShortPassword_ReturnsBadRequest(string password)
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"short_pw_probe","display_name":"A","password":"{{password}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_Response_DoesNotExposePasswordOrHash()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"no_leak_probe","display_name":"A","password":"{{DefaultPassword}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", body, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("argon2", body, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetChat_ByNonMember_ReturnsNotFound()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
using var request = Request(HttpMethod.Get, $"/api/v1/chats/{chatId}", eve);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("not_found", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListChats_ShowsOnlyChatsOfCurrentUser()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var shared = await CreateChatAsync(client, alice, bob);
|
||||
var other = await CreateChatAsync(client, eve);
|
||||
|
||||
using var request = Request(HttpMethod.Get, "/api/v1/chats", bob);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
var ids = page.GetProperty("items").EnumerateArray().Select(c => c.GetProperty("id").GetGuid()).ToList();
|
||||
|
||||
Assert.Contains(shared, ids);
|
||||
Assert.DoesNotContain(other, ids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateChat_WithUnknownMember_ReturnsBadRequestAndCreatesNothing()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", alice,
|
||||
Json($$"""{"title":"X","member_ids":["{{alice.Id}}","{{Guid.NewGuid()}}"]}"""));
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var list = Request(HttpMethod.Get, "/api/v1/chats", alice);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(list));
|
||||
Assert.Empty(page.GetProperty("items").EnumerateArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendMessage_ToForeignChat_ReturnsNotFound()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
var response = await SendMessageAsync(client, eve, chatId, "чужое");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task SendMessage_WithEmptyText_ReturnsBadRequest(string text)
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice);
|
||||
|
||||
var response = await SendMessageAsync(client, alice, chatId, text);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendMessage_SenderIsTakenFromSession_NotFromRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", alice,
|
||||
Json($$"""{"text":"привет","sender_id":"{{bob.Id}}"}"""));
|
||||
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString("N"));
|
||||
var withSender = await client.SendAsync(request);
|
||||
var ok = await SendMessageAsync(client, alice, chatId, "привет");
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, withSender.StatusCode); // sender_id в запросе не принимается
|
||||
Assert.Equal(alice.Id, (await ReadJsonAsync(ok)).GetProperty("sender_id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_WalksAllPagesWithoutGapsOrDuplicates()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
const int total = 7;
|
||||
var sent = new List<Guid>();
|
||||
for (var i = 0; i < total; i++)
|
||||
{
|
||||
var response = await SendMessageAsync(client, i % 2 == 0 ? alice : bob, chatId, $"сообщение {i}");
|
||||
sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
var received = new List<Guid>();
|
||||
string? cursor = null;
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit=3" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, alice);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid()));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
pages++;
|
||||
}
|
||||
while (cursor is not null && pages < 10);
|
||||
|
||||
Assert.Equal(3, pages);
|
||||
Assert.Equal(total, received.Count);
|
||||
// Один автор в одном чате: порядок истории совпадает с порядком отправки.
|
||||
Assert.Equal(sent, received);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_WithCursorFromAnotherChat_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat1 = await CreateChatAsync(client, alice);
|
||||
var chat2 = await CreateChatAsync(client, alice);
|
||||
await SendMessageAsync(client, alice, chat1, "a");
|
||||
await SendMessageAsync(client, alice, chat1, "b");
|
||||
using var first = Request(HttpMethod.Get, $"/api/v1/chats/{chat1}/messages?limit=1", alice);
|
||||
var cursor = (await ReadJsonAsync(await client.SendAsync(first))).GetProperty("next_cursor").GetString()!;
|
||||
|
||||
using var request = Request(HttpMethod.Get,
|
||||
$"/api/v1/chats/{chat2}/messages?cursor={Uri.EscapeDataString(cursor)}", alice);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_ReturnsSameOrderForAnyPageSize()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice);
|
||||
var sent = new List<Guid>();
|
||||
for (var i = 0; i < 120; i++)
|
||||
{
|
||||
var response = await SendMessageAsync(client, alice, chatId, $"m{i}");
|
||||
sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
var baseline = await ReadAllMessagesAsync(client, chatId, alice, 100);
|
||||
Assert.Equal(sent, baseline);
|
||||
foreach (var limit in new[] { 1, 7, 50 })
|
||||
{
|
||||
var received = await ReadAllMessagesAsync(client, chatId, alice, limit);
|
||||
Assert.Equal(baseline, received);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_AfterConcurrentSends_IsOrderedByTimeThenId()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var users = new List<TestUser>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
users.Add(await CreateUserAsync(client));
|
||||
}
|
||||
|
||||
var chatId = await CreateChatAsync(client, users[0], users.Skip(1).ToArray());
|
||||
|
||||
var sends = Enumerable.Range(0, 300).Select(i => SendMessageAsync(client, users[i % 10], chatId, $"m{i}"));
|
||||
foreach (var response in await Task.WhenAll(sends))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
var items = new List<(string CreatedAt, Guid Id)>();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit=100" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, users[0]);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
items.AddRange(page.GetProperty("items").EnumerateArray()
|
||||
.Select(m => (m.GetProperty("created_at").GetString()!, m.GetProperty("id").GetGuid())));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
}
|
||||
while (cursor is not null);
|
||||
|
||||
Assert.Equal(300, items.Count);
|
||||
Assert.Equal(300, items.Select(x => x.Id).Distinct().Count());
|
||||
// Серверное время строго возрастает внутри чата (см. last_message_at), поэтому порядок истории — порядок записи.
|
||||
Assert.Equal(300, items.Select(x => x.CreatedAt).Distinct().Count());
|
||||
Assert.Equal(items.OrderBy(x => x.CreatedAt, StringComparer.Ordinal).ToList(), items);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"USERNAME":"probe_case_a","display_name":"A","password":"correct horse battery staple"}""")]
|
||||
[InlineData("""{"username":"probe_case_b","Display_Name":"A","password":"correct horse battery staple"}""")]
|
||||
[InlineData("""{"Username":"probe_case_c","display_name":"A","password":"correct horse battery staple"}""")]
|
||||
public async Task CreateUser_WithDifferentlyCasedFieldNames_ReturnsBadRequest(string body)
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", Json(body));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class AuthTests(ApiFixture fixture)
|
||||
{
|
||||
private static readonly string[] ProtectedGets =
|
||||
[
|
||||
"/api/v1/users/me",
|
||||
"/api/v1/chats",
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000001",
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000001/messages"
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ReturnsOpaqueBearerSession()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var response = await LoginAsync(client, user.Username, user.Password);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var json = await ReadJsonAsync(response);
|
||||
Assert.Equal("Bearer", json.GetProperty("token_type").GetString());
|
||||
Assert.True(json.GetProperty("token").GetString()!.Length >= 43); // 256 бит в base64url
|
||||
Assert.Equal(user.Id, json.GetProperty("user").GetProperty("id").GetGuid());
|
||||
Assert.DoesNotContain("password", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_AcceptsColonInPassword()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var username = "colon" + Guid.NewGuid().ToString("N")[..8];
|
||||
await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{username}}","display_name":"A","password":"pass:with:colons-123"}"""));
|
||||
|
||||
var response = await LoginAsync(client, username, "pass:with:colons-123");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WrongPasswordAndUnknownUser_GiveIdenticalUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var wrongPassword = await LoginAsync(client, user.Username, "totally-wrong-password");
|
||||
var unknownUser = await LoginAsync(client, "nobody_" + Guid.NewGuid().ToString("N")[..8], DefaultPassword);
|
||||
|
||||
foreach (var response in new[] { wrongPassword, unknownUser })
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Basic realm=\"messenger\", charset=\"UTF-8\"", response.Headers.WwwAuthenticate.ToString());
|
||||
Assert.Equal("unauthorized", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
var a = (await ReadJsonAsync(wrongPassword)).GetProperty("error").GetProperty("message").GetString();
|
||||
var b = (await ReadJsonAsync(unknownUser)).GetProperty("error").GetProperty("message").GetString();
|
||||
Assert.Equal(a, b);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Basic !!!not-base64")]
|
||||
[InlineData("Basic bm9jb2xvbg==")] // "nocolon"
|
||||
[InlineData("Bearer sometoken")]
|
||||
[InlineData("")]
|
||||
public async Task Login_WithMalformedAuthorization_ReturnsUnauthorized(string header)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions");
|
||||
if (header.Length > 0)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Authorization", header);
|
||||
}
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.StartsWith("Basic", response.Headers.WwwAuthenticate.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ProtectedUrls))]
|
||||
public async Task ProtectedEndpoints_WithoutToken_ReturnUnauthorizedWithBearerChallenge(string url)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync(url);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString());
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> ProtectedUrls() => ProtectedGets.Select(u => new object[] { u });
|
||||
|
||||
[Fact]
|
||||
public async Task ProtectedEndpoint_WithBasicAuth_ReturnsUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(user.Username, user.Password));
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task XUserIdHeader_IsIgnored()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
|
||||
// Без токена X-User-Id не даёт доступа.
|
||||
using var anonymous = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me");
|
||||
anonymous.Headers.Add("X-User-Id", alice.Id.ToString());
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(anonymous)).StatusCode);
|
||||
|
||||
// С токеном — владелец сессии не подменяется.
|
||||
using var spoofed = Request(HttpMethod.Get, "/api/v1/users/me", alice);
|
||||
spoofed.Headers.Add("X-User-Id", eve.Id.ToString());
|
||||
var me = await ReadJsonAsync(await client.SendAsync(spoofed));
|
||||
Assert.Equal(alice.Id, me.GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnauthenticatedPostWithMalformedBody_ReturnsUnauthorizedNotBadRequest()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/chats", Json("{bad"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); // сначала аутентификация
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Logout_RevokesTokenAndSecondLogoutIsUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
using var first = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
var firstResponse = await client.SendAsync(first);
|
||||
Assert.Equal(HttpStatusCode.NoContent, firstResponse.StatusCode);
|
||||
Assert.Equal(0, firstResponse.Content.Headers.ContentLength ?? 0);
|
||||
|
||||
using var again = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(again)).StatusCode);
|
||||
using var me = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(me)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogoutOfOneSession_DoesNotAffectAnotherSessionOfSameUser()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
var secondLogin = await ReadJsonAsync(await LoginAsync(client, user.Username, user.Password));
|
||||
var second = user with { Token = secondLogin.GetProperty("token").GetString()! };
|
||||
|
||||
using var logout = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
await client.SendAsync(logout);
|
||||
|
||||
using var me = Request(HttpMethod.Get, "/api/v1/users/me", second);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(me)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredSession_IsRejected()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using var before = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(before)).StatusCode);
|
||||
|
||||
// Состарим сессию в БД: created_at < expires_at < now (ограничение таблицы требует expires_at > created_at).
|
||||
await using (var db = await fixture.OpenConnectionAsync())
|
||||
await using (var age = new Npgsql.NpgsqlCommand(
|
||||
"update sessions set created_at = now() - interval '10 seconds', expires_at = now() - interval '5 seconds' where user_id = @u", db))
|
||||
{
|
||||
age.Parameters.AddWithValue("u", user.Id);
|
||||
Assert.Equal(1, await age.ExecuteNonQueryAsync());
|
||||
}
|
||||
|
||||
using var after = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(after)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShortSessionTtl_ExpiresSessionByItself()
|
||||
{
|
||||
// Отдельный экземпляр приложения с SESSION_TTL_SECONDS=2 поверх той же БД: никаких подмен данных в таблице.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2"));
|
||||
using var client = app.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
using (var alive = Request(HttpMethod.Get, "/api/v1/users/me", user))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(alive)).StatusCode);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
using var expired = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var response = await client.SendAsync(expired);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString());
|
||||
// Истёкшая сессия не продлевается: повторный вход выдаёт новую.
|
||||
Assert.Equal(HttpStatusCode.Created, (await LoginAsync(client, user.Username, user.Password)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SessionsTable_StoresTokenHashNotToken()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var query = new Npgsql.NpgsqlCommand(
|
||||
"select token_hash from sessions where user_id = @u", db);
|
||||
query.Parameters.AddWithValue("u", user.Id);
|
||||
var stored = (byte[])(await query.ExecuteScalarAsync())!;
|
||||
|
||||
Assert.Equal(32, stored.Length);
|
||||
Assert.NotEqual(System.Text.Encoding.UTF8.GetBytes(user.Token), stored);
|
||||
Assert.Equal(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(user.Token)), stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PasswordsAreStoredAsArgon2id()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var query = new Npgsql.NpgsqlCommand("select password_hash from users where id = @u", db);
|
||||
query.Parameters.AddWithValue("u", user.Id);
|
||||
var hash = (string)(await query.ExecuteScalarAsync())!;
|
||||
|
||||
Assert.StartsWith("$argon2id$", hash);
|
||||
Assert.DoesNotContain(user.Password, hash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class CacheTests(ApiFixture fixture)
|
||||
{
|
||||
private static string Header(HttpResponseMessage response, string name) =>
|
||||
response.Headers.TryGetValues(name, out var values) ? values.First() : "";
|
||||
|
||||
private static async Task<HttpResponseMessage> GetPageAsync(
|
||||
HttpClient client, TestUser user, Guid chatId, int limit = 50, string? cursor = null)
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, user);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<(TestUser Alice, TestUser Bob, Guid Chat)> ChatWithMessagesAsync(HttpClient client, int messages)
|
||||
{
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice, bob);
|
||||
for (var i = 0; i < messages; i++)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, $"m{i}")).StatusCode);
|
||||
}
|
||||
|
||||
return (alice, bob, chat);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecondRead_IsServedFromCache_WithFewerSqlQueries_AndIdenticalBody()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 3);
|
||||
|
||||
var first = await GetPageAsync(client, bob, chat);
|
||||
var second = await GetPageAsync(client, bob, chat);
|
||||
|
||||
Assert.Equal("miss", Header(first, "X-Cache"));
|
||||
Assert.Equal("hit", Header(second, "X-Cache"));
|
||||
// miss: сессия + версия/доступ + страница; hit: сессия + версия/доступ.
|
||||
Assert.Equal("3", Header(first, "X-Db-Queries"));
|
||||
Assert.Equal("2", Header(second, "X-Db-Queries"));
|
||||
Assert.Equal(await first.Content.ReadAsStringAsync(), await second.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadAfterWrite_NeverReturnsStaleCachedPage()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (alice, bob, chat) = await ChatWithMessagesAsync(client, 2);
|
||||
await GetPageAsync(client, bob, chat); // прогрели кэш
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache"));
|
||||
|
||||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
var sent = await SendMessageAsync(client, alice, chat, $"new {i}");
|
||||
var id = (await ReadJsonAsync(sent)).GetProperty("id").GetGuid();
|
||||
|
||||
// Сразу после подтверждённой записи (201) следующее чтение обязано содержать новое сообщение.
|
||||
var ids = await ReadAllMessagesAsync(client, chat, bob, 100);
|
||||
Assert.Contains(id, ids);
|
||||
Assert.Equal(3 + i, ids.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FlushedCache_DoesNotChangeResults()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 5);
|
||||
var before = await ReadAllMessagesAsync(client, chat, bob, 2);
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat, 2), "X-Cache"));
|
||||
|
||||
await fixture.FlushCacheAsync();
|
||||
|
||||
var response = await GetPageAsync(client, bob, chat, 2);
|
||||
Assert.Equal("miss", Header(response, "X-Cache"));
|
||||
Assert.Equal(before, await ReadAllMessagesAsync(client, chat, bob, 2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CachedPage_IsNotVisibleToNonMember()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 2);
|
||||
var eve = await CreateUserAsync(client);
|
||||
await GetPageAsync(client, bob, chat);
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache"));
|
||||
|
||||
var response = await GetPageAsync(client, eve, chat);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // доступ проверяется до обращения к кэшу
|
||||
Assert.DoesNotContain("m0", await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PagesWithDifferentLimitsAndCursors_AreCachedSeparately()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 9);
|
||||
|
||||
var firstPass = await ReadAllMessagesAsync(client, chat, bob, 4);
|
||||
var secondPass = await ReadAllMessagesAsync(client, chat, bob, 4); // все страницы уже в кэше
|
||||
var otherLimit = await ReadAllMessagesAsync(client, chat, bob, 3);
|
||||
|
||||
Assert.Equal(9, firstPass.Count);
|
||||
Assert.Equal(firstPass, secondPass);
|
||||
Assert.Equal(firstPass, otherLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnavailableCache_IsBypassed_AndRequestsStillSucceed()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 3);
|
||||
var expected = await ReadAllMessagesAsync(client, chat, bob, 100);
|
||||
|
||||
// Второй экземпляр приложения, у которого кэш указывает на закрытый порт.
|
||||
await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1"));
|
||||
using var brokenClient = broken.CreateClient();
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var response = await GetPageAsync(brokenClient, bob, chat);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("bypass", Header(response, "X-Cache"));
|
||||
}
|
||||
|
||||
Assert.Equal(expected, await ReadAllMessagesAsync(brokenClient, chat, bob, 100));
|
||||
// Запись тоже не зависит от кэша.
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(brokenClient, bob, chat, "при отказе кэша")).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnavailableCache_DoesNotTrustAnonymousRequests()
|
||||
{
|
||||
await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1"));
|
||||
using var client = broken.CreateClient();
|
||||
|
||||
var response = await client.GetAsync($"/api/v1/chats/{Guid.NewGuid()}/messages");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class ConcurencyTests(ApiFixture fixture)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Create100MessagesBy10DifferentUsers_Concurrent()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var users = new List<TestUser>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
users.Add(await CreateUserAsync(client));
|
||||
}
|
||||
|
||||
var chat = await CreateChatAsync(client, users[0], users.Skip(1).ToArray());
|
||||
|
||||
var messageTasks = Enumerable.Range(0, 100)
|
||||
.Select(i => SendMessageAsync(client, users[i % 10], chat, $"Message {i + 1} from {users[i % 10].Username}"))
|
||||
.ToList();
|
||||
|
||||
foreach (var response in await Task.WhenAll(messageTasks))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
var messages = await ReadAllMessagesAsync(client, chat, users[0], 7);
|
||||
|
||||
Assert.Equal(100, messages.Count);
|
||||
Assert.Equal(100, messages.Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterSameUsernameConcurrently_ExactlyOneSucceeds_NoServerErrors()
|
||||
{
|
||||
// Проверяется гарантия уникального индекса, а не скорость железа: очередь хеширования делаем практически
|
||||
// неограниченной по времени (по умолчанию лишние запросы получают 503, см. следующий тест).
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "120"));
|
||||
using var client = app.CreateClient();
|
||||
var username = "race" + Guid.NewGuid().ToString("N")[..10];
|
||||
|
||||
var attempts = Enumerable.Range(0, 20).Select(_ => client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{username}}","display_name":"Гонка","password":"{{DefaultPassword}}"}""")));
|
||||
var statuses = (await Task.WhenAll(attempts)).Select(r => r.StatusCode).ToList();
|
||||
|
||||
Assert.Single(statuses, HttpStatusCode.Created);
|
||||
Assert.Equal(19, statuses.Count(s => s == HttpStatusCode.Conflict));
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var count = new Npgsql.NpgsqlCommand("select count(*) from users where username = @u", db);
|
||||
count.Parameters.AddWithValue("u", username);
|
||||
Assert.Equal(1L, await count.ExecuteScalarAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegistrationBurstBeyondHashingCapacity_GetsBoundedUnavailable_NotServerError()
|
||||
{
|
||||
// Один слот Argon2 и ожидание 50 мс: пачка регистраций разных пользователей упирается в лимит.
|
||||
// Лишние запросы получают 503 unavailable (а не 500 и не зависание), принятые — 201.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("PASSWORD_HASH_CONCURRENCY", "1")
|
||||
.UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "0.05"));
|
||||
using var client = app.CreateClient();
|
||||
var prefix = "burst" + Guid.NewGuid().ToString("N")[..6];
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{prefix}}_{{i}}","display_name":"Пачка","password":"{{DefaultPassword}}"}"""))));
|
||||
var statuses = responses.Select(r => r.StatusCode).ToList();
|
||||
|
||||
Assert.All(statuses, s => Assert.True(s is HttpStatusCode.Created or HttpStatusCode.ServiceUnavailable, $"неожиданный статус {s}"));
|
||||
Assert.Contains(HttpStatusCode.Created, statuses);
|
||||
Assert.Contains(HttpStatusCode.ServiceUnavailable, statuses);
|
||||
var rejected = responses.First(r => r.StatusCode == HttpStatusCode.ServiceUnavailable);
|
||||
Assert.Equal("unavailable", await ErrorCodeAsync(rejected));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Testcontainers.PostgreSql;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class DependencyFailureTests(ApiFixture fixture)
|
||||
{
|
||||
private static int FreePort()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
return ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DatabaseDown_Returns503_NeverTrustsAnonymous_AndRecovers()
|
||||
{
|
||||
// Отдельный контейнер БД, который тест останавливает и запускает снова на том же порту.
|
||||
var port = FreePort();
|
||||
await using var pg = new PostgreSqlBuilder().WithImage(ApiFixture.PostgresImage).WithPortBinding(port, 5432).Build();
|
||||
await pg.StartAsync();
|
||||
var file = ApiFixture.WriteConnectionFile(pg.GetConnectionString());
|
||||
try
|
||||
{
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("DATABASE_URL_FILE", file)
|
||||
.UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "2"));
|
||||
using var client = app.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using (var ok = Request(HttpMethod.Get, "/api/v1/users/me", user))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(ok)).StatusCode);
|
||||
}
|
||||
|
||||
await pg.StopAsync();
|
||||
|
||||
// Аутентифицированный запрос: ограниченная ошибка 503 без внутренних деталей.
|
||||
using var down = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var downResponse = await client.SendAsync(down);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, downResponse.StatusCode);
|
||||
Assert.Equal("unavailable", await ErrorCodeAsync(downResponse));
|
||||
var body = await downResponse.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Npgsql", body);
|
||||
Assert.DoesNotContain("Host=", body);
|
||||
Assert.True(downResponse.Headers.Contains("X-Request-Id"));
|
||||
|
||||
// Анонимный запрос не становится доверенным: без токена по-прежнему 401, а не 200/503 «как гость».
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/v1/chats")).StatusCode);
|
||||
// Токен, который нельзя проверить, не принимается.
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable,
|
||||
(await LoginAsync(client, user.Username, user.Password)).StatusCode);
|
||||
// Готовность отражает отказ, живость — нет.
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, (await client.GetAsync("/health/ready")).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/health/live")).StatusCode);
|
||||
|
||||
// Восстановление: после запуска БД тот же токен снова работает (данные не потеряны), без перезапуска API.
|
||||
await pg.StartAsync();
|
||||
var recovered = false;
|
||||
var started = Stopwatch.StartNew();
|
||||
while (started.Elapsed < TimeSpan.FromSeconds(30) && !recovered)
|
||||
{
|
||||
using var retry = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
recovered = (await client.SendAsync(retry)).StatusCode == HttpStatusCode.OK;
|
||||
if (!recovered)
|
||||
{
|
||||
await Task.Delay(500);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(recovered, "API не восстановился после возврата PostgreSQL");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExhaustedConnectionPool_ReturnsBoundedError()
|
||||
{
|
||||
using var setup = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(setup);
|
||||
|
||||
// Пул из одного соединения и короткое ожидание: пока тест держит единственное соединение, запросы не зависают.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("DB_MAX_POOL_SIZE", "1")
|
||||
.UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "1"));
|
||||
using var client = app.CreateClient();
|
||||
|
||||
using var scope = app.Services.CreateScope();
|
||||
var held = scope.ServiceProvider.GetRequiredService<Data.MessengerDbContext>();
|
||||
await held.Database.OpenConnectionAsync();
|
||||
try
|
||||
{
|
||||
var started = Stopwatch.StartNew();
|
||||
using var request = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var response = await client.SendAsync(request);
|
||||
started.Stop();
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
Assert.True(started.Elapsed < TimeSpan.FromSeconds(6), $"ответ занял {started.Elapsed}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await held.Database.CloseConnectionAsync();
|
||||
}
|
||||
|
||||
// После освобождения соединения сервис работает.
|
||||
using var after = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(after)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedMessageInsert_RollsBackVersionAndTimestamp()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "до сбоя")).StatusCode);
|
||||
|
||||
var marker = "boom-" + Guid.NewGuid().ToString("N");
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
// Сбой «после UPDATE чата, во время INSERT сообщения»: триггер БД отклоняет сообщение с маркером.
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.text = '{{marker}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
var versionBefore = await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat));
|
||||
var lastBefore = await fixture.ScalarAsync<DateTime?>("select last_message_at from chats where id = @c", ("c", chat));
|
||||
|
||||
var failed = await SendMessageAsync(client, alice, chat, marker);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
|
||||
var body = await failed.Content.ReadAsStringAsync();
|
||||
Assert.Contains("internal_error", body);
|
||||
Assert.DoesNotContain("injected", body); // внутренние детали не раскрываются
|
||||
Assert.Equal(versionBefore, await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat)));
|
||||
Assert.Equal(lastBefore, await fixture.ScalarAsync<DateTime?>("select last_message_at from chats where id = @c", ("c", chat)));
|
||||
Assert.Equal(1L, await fixture.ScalarAsync<long>("select count(*) from messages where chat_id = @c", ("c", chat)));
|
||||
|
||||
// Блокировка строки чата снята, следующая запись проходит и версия растёт ровно на 1.
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "после сбоя")).StatusCode);
|
||||
Assert.Equal(versionBefore + 1, await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON messages; DROP FUNCTION fail_{suffix}();");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedChatMemberInsert_RollsBackWholeChat()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
var title = "rollback-" + suffix;
|
||||
|
||||
// Сбой при добавлении второго участника, уже после вставки строки чата и первого участника.
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.user_id = '{{bob.Id}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", alice,
|
||||
Json($$"""{"title":"{{title}}","member_ids":["{{alice.Id}}","{{bob.Id}}"]}"""));
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>("select count(*) from chats where title = @t", ("t", title)));
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>(
|
||||
"select count(*) from chat_members where user_id in (@a, @b) ", ("a", alice.Id), ("b", bob.Id)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON chat_members; DROP FUNCTION fail_{suffix}();");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Net;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class HealthTests(ApiFixture fixture)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Live_ReturnsOk()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/health/live");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ready_ReturnsOkWhenDatabaseIsAvailable()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/health/ready");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Net;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
// lab3: общая идемпотентность отправки сообщения. «Разные реплики» в тесте моделируются разными экземплярами приложения
|
||||
// (fixture.WithWebHostBuilder) с общей PostgreSQL — ровно так же, как в Compose работают реплики за балансировщиком.
|
||||
[Collection("api")]
|
||||
public class IdempotencyTests(ApiFixture fixture)
|
||||
{
|
||||
private static string NewKey() => Guid.NewGuid().ToString("N");
|
||||
|
||||
private static async Task<int> CountMessagesAsync(HttpClient client, Guid chat, TestUser user) =>
|
||||
(await ReadAllMessagesAsync(client, chat, user, 100)).Count;
|
||||
|
||||
[Fact]
|
||||
public async Task Replay_ReturnsSameCodeAndSameMessage_WithoutDuplicate()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var first = await SendMessageAsync(client, alice, chat, "привет", key);
|
||||
var second = await SendMessageAsync(client, alice, chat, "привет", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
Assert.Equal((await ReadJsonAsync(first)).ToString(), (await ReadJsonAsync(second)).ToString());
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SameKeyDifferentBody_Conflict_AndOriginalIsKept()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
await SendMessageAsync(client, alice, chat, "первое", key);
|
||||
var other = await SendMessageAsync(client, alice, chat, "второе", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, other.StatusCode);
|
||||
Assert.Equal("conflict", await ErrorCodeAsync(other));
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("has space")]
|
||||
[InlineData("кириллица")]
|
||||
public async Task MissingOrInvalidKey_BadRequest(string? key)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", alice,
|
||||
Json("""{"text":"x"}"""));
|
||||
if (key is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Idempotency-Key", key);
|
||||
}
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(0, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task KeyTooLong_BadRequest_ButMaxLengthAccepted()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
|
||||
var tooLong = await SendMessageAsync(client, alice, chat, "x", new string('a', 129));
|
||||
var maxLength = await SendMessageAsync(client, alice, chat, "x", new string('a', 128));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, tooLong.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, maxLength.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SameKeyIsIndependent_ForDifferentUsersAndDifferentChats()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chat1 = await CreateChatAsync(client, alice, bob);
|
||||
var chat2 = await CreateChatAsync(client, alice, bob);
|
||||
var key = NewKey();
|
||||
|
||||
var statuses = new[]
|
||||
{
|
||||
(await SendMessageAsync(client, alice, chat1, "a1", key)).StatusCode,
|
||||
(await SendMessageAsync(client, bob, chat1, "b1", key)).StatusCode,
|
||||
(await SendMessageAsync(client, alice, chat2, "a2", key)).StatusCode,
|
||||
};
|
||||
|
||||
Assert.All(statuses, s => Assert.Equal(HttpStatusCode.Created, s));
|
||||
Assert.Equal(2, await CountMessagesAsync(client, chat1, alice));
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat2, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replay_StillRequiresValidSessionAndAccess()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
await SendMessageAsync(client, alice, chat, "секрет", key);
|
||||
|
||||
// Посторонний не может «прочитать» чужой результат по ключу; без токена — 401.
|
||||
var asEve = await SendMessageAsync(client, eve, chat, "секрет", key);
|
||||
using var anonymous = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", null, Json("""{"text":"секрет"}"""));
|
||||
anonymous.Headers.Add("Idempotency-Key", key);
|
||||
var noToken = await client.SendAsync(anonymous);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, asEve.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentReplays_OnOneInstance_CreateExactlyOneMessage()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 30)
|
||||
.Select(_ => Task.Run(() => SendMessageAsync(client, alice, chat, "гонка", key))));
|
||||
|
||||
Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode));
|
||||
var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid()));
|
||||
Assert.Single(ids.Distinct());
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentReplays_ThroughDifferentInstances_CreateExactlyOneMessage()
|
||||
{
|
||||
// Три независимых экземпляра приложения (как три реплики) с общей PostgreSQL.
|
||||
await using var replicaB = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-b"));
|
||||
await using var replicaC = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-c"));
|
||||
using var a = fixture.CreateClient();
|
||||
using var b = replicaB.CreateClient();
|
||||
using var c = replicaC.CreateClient();
|
||||
|
||||
var alice = await CreateUserAsync(a); // сессия создана на A и действует на B и C: сессии общие
|
||||
var chat = await CreateChatAsync(a, alice);
|
||||
var clients = new[] { a, b, c };
|
||||
|
||||
for (var round = 0; round < 5; round++)
|
||||
{
|
||||
var key = NewKey();
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 30)
|
||||
.Select(i => Task.Run(() => SendMessageAsync(clients[i % 3], alice, chat, $"гонка {round}", key))));
|
||||
|
||||
Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode));
|
||||
var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid()));
|
||||
Assert.Single(ids.Distinct());
|
||||
}
|
||||
|
||||
Assert.Equal(5, await CountMessagesAsync(b, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentSameKeyWithDifferentBodies_ExactlyOneWins_OthersConflict()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 10)
|
||||
.Select(i => Task.Run(() => SendMessageAsync(client, alice, chat, $"вариант {i}", key))));
|
||||
|
||||
var created = responses.Count(r => r.StatusCode == HttpStatusCode.Created);
|
||||
var conflicts = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict);
|
||||
Assert.True(created >= 1 && created + conflicts == 10, $"created={created}, conflicts={conflicts}");
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedWrite_IsNotRemembered_AndCanBeRetriedWithSameKey()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
// Принудительная ошибка БД при вставке сообщения: транзакция (вместе с ключом) откатывается.
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_idem_{{suffix}}() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'forced failure' USING ERRCODE = '53000'; END $$ LANGUAGE plpgsql;
|
||||
CREATE TRIGGER tr_idem_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW WHEN (NEW.chat_id = '{{chat}}') EXECUTE FUNCTION fail_idem_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
var failed = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
Assert.True((int)failed.StatusCode >= 500, $"expected 5xx, got {(int)failed.StatusCode}");
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>("select count(*) from idempotency_keys where chat_id = @c", ("c", chat)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_idem_{suffix} ON messages; DROP FUNCTION fail_idem_{suffix}();");
|
||||
}
|
||||
|
||||
var retried = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
var again = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, retried.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, again.StatusCode);
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredKey_CanBeReused_AsNewMessage()
|
||||
{
|
||||
await using var shortTtl = fixture.WithWebHostBuilder(b => b.UseSetting("IDEMPOTENCY_TTL_SECONDS", "1"));
|
||||
using var client = shortTtl.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var first = await SendMessageAsync(client, alice, chat, "срок", key);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1500));
|
||||
var second = await SendMessageAsync(client, alice, chat, "срок", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
Assert.NotEqual(
|
||||
(await ReadJsonAsync(first)).GetProperty("id").GetGuid(),
|
||||
(await ReadJsonAsync(second)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryResponse_HasInstanceId_IncludingErrorsAndHealth()
|
||||
{
|
||||
await using var replica = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-x"));
|
||||
using var client = replica.CreateClient();
|
||||
|
||||
var health = await client.GetAsync("/health/live");
|
||||
var ready = await client.GetAsync("/health/ready");
|
||||
var unauthorized = await client.GetAsync("/api/v1/users/me");
|
||||
var notFound = await client.GetAsync("/no/such/route");
|
||||
var badJson = await client.PostAsync("/api/v1/users", Json("{broken"));
|
||||
|
||||
foreach (var response in new[] { health, ready, unauthorized, notFound, badJson })
|
||||
{
|
||||
Assert.Equal("replica-x", Assert.Single(response.Headers.GetValues("X-Instance-Id")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" Version="4.16.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Messenger.Api\Messenger.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,69 @@
|
||||
using Messenger.Api.Services;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
public class PasswordHasherTests
|
||||
{
|
||||
private readonly Argon2PasswordHasher _hasher = new(new PasswordHashingSettings(4, TimeSpan.FromSeconds(30)));
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_IsArgon2idPhcString_WithoutPlaintext()
|
||||
{
|
||||
var hash = await _hasher.HashAsync("correct horse battery staple", CancellationToken.None);
|
||||
|
||||
Assert.StartsWith("$argon2id$", hash);
|
||||
Assert.DoesNotContain("correct horse", hash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_UsesRandomSalt()
|
||||
{
|
||||
var a = await _hasher.HashAsync("same-password-123", CancellationToken.None);
|
||||
var b = await _hasher.HashAsync("same-password-123", CancellationToken.None);
|
||||
|
||||
Assert.NotEqual(a, b);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("correct horse battery staple")]
|
||||
[InlineData("пароль-с-юникодом-и:двоеточием-12")]
|
||||
public async Task Verify_AcceptsCorrect_RejectsWrong(string password)
|
||||
{
|
||||
var hash = await _hasher.HashAsync(password, CancellationToken.None);
|
||||
|
||||
Assert.True(await _hasher.VerifyAsync(hash, password, CancellationToken.None));
|
||||
Assert.False(await _hasher.VerifyAsync(hash, password + "x", CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_DoesNotTruncateLongPasswords()
|
||||
{
|
||||
// Это ограничение bcrypt (72 байта); Argon2id его не имеет. Пароли отличаются только хвостом.
|
||||
var prefix = new string('я', 60); // 120 байт в UTF-8
|
||||
var hash = await _hasher.HashAsync(prefix + "A", CancellationToken.None);
|
||||
|
||||
Assert.False(await _hasher.VerifyAsync(hash, prefix + "B", CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_WhenAllSlotsAreBusy_FailsWithBusyException()
|
||||
{
|
||||
// Один слот и почти нулевое ожидание: параллельные вызовы не копят память, лишние получают исключение (→ 503).
|
||||
var hasher = new Argon2PasswordHasher(new PasswordHashingSettings(1, TimeSpan.FromMilliseconds(20)));
|
||||
|
||||
var attempts = await Task.WhenAll(Enumerable.Range(0, 6).Select(async _ =>
|
||||
{
|
||||
try { await hasher.HashAsync("some-long-enough-password", CancellationToken.None); return true; }
|
||||
catch (PasswordHasherBusyException) { return false; }
|
||||
}));
|
||||
|
||||
Assert.Contains(true, attempts); // кто-то получил слот
|
||||
Assert.Contains(false, attempts); // остальные получили контролируемый отказ
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_UnknownUser_ReturnsFalse()
|
||||
{
|
||||
Assert.False(await _hasher.VerifyAsync(null, "any-password-123", CancellationToken.None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace Messenger.Api.Data;
|
||||
|
||||
// Используется только командами `dotnet ef`. Для генерации миграций подключение к БД не открывается;
|
||||
// для `dotnet ef database update` строка берётся из MESSENGER_DESIGN_CONNECTION.
|
||||
public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MessengerDbContext>
|
||||
{
|
||||
public MessengerDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var connection = Environment.GetEnvironmentVariable("MESSENGER_DESIGN_CONNECTION")
|
||||
?? "Host=localhost;Database=messenger;Username=design;Password=design";
|
||||
var options = new DbContextOptionsBuilder<MessengerDbContext>()
|
||||
.UseNpgsql(connection)
|
||||
.UseSnakeCaseNamingConvention()
|
||||
.Options;
|
||||
return new MessengerDbContext(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace Messenger.Api.Data;
|
||||
|
||||
// Строки таблиц. API-модели (Messenger.Api.Models) остаются отдельными: в них нет password_hash и служебных полей.
|
||||
|
||||
public sealed class UserEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
// Результат Argon2id (PHC-строка с солью и параметрами). Наружу не отдаётся никогда.
|
||||
public string PasswordHash { get; set; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ChatEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
|
||||
// Версия истории: растёт на 1 в той же транзакции, что и вставка сообщения (UPDATE ... RETURNING).
|
||||
// Источник версии для ключей кэша; одновременно сериализует записи в один чат (см. DESIGN).
|
||||
public long HistoryVersion { get; set; }
|
||||
|
||||
// Время последнего сообщения. Обновляется тем же UPDATE, что и версия: следующее сообщение получает
|
||||
// created_at строго больше этого значения, поэтому порядок (created_at, id) совпадает с порядком коммитов.
|
||||
public DateTimeOffset? LastMessageAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ChatMemberEntity
|
||||
{
|
||||
public Guid ChatId { get; set; }
|
||||
public Guid UserId { get; set; }
|
||||
}
|
||||
|
||||
public sealed class MessageEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid ChatId { get; set; }
|
||||
public Guid SenderId { get; set; }
|
||||
public string Text { get; set; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class SessionEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
// SHA-256 от токена. Сам токен в БД не хранится: утечка БД не даёт действующих Bearer-токенов.
|
||||
public byte[] TokenHash { get; set; } = Array.Empty<byte>();
|
||||
public Guid UserId { get; set; }
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public DateTimeOffset ExpiresAt { get; set; }
|
||||
public DateTimeOffset? RevokedAt { get; set; }
|
||||
}
|
||||
|
||||
// Результат идемпотентной отправки сообщения. Область уникальности: пользователь + чат (метод и путь у эндпоинта один:
|
||||
// POST /api/v1/chats/{chat_id}/messages) + ключ. Строка создаётся в той же транзакции, что и сообщение.
|
||||
public sealed class IdempotencyKeyEntity
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public Guid ChatId { get; set; }
|
||||
public string Key { get; set; } = string.Empty;
|
||||
// SHA-256 от смысла запроса (см. IdempotencyKeys.RequestHash): другой хеш при том же ключе → 409.
|
||||
public byte[] RequestHash { get; set; } = Array.Empty<byte>();
|
||||
public Guid MessageId { get; set; }
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public DateTimeOffset ExpiresAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Messenger.Api.Data;
|
||||
|
||||
public sealed class MessengerDbContext(DbContextOptions<MessengerDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<UserEntity> Users => Set<UserEntity>();
|
||||
public DbSet<ChatEntity> Chats => Set<ChatEntity>();
|
||||
public DbSet<ChatMemberEntity> ChatMembers => Set<ChatMemberEntity>();
|
||||
public DbSet<MessageEntity> Messages => Set<MessageEntity>();
|
||||
public DbSet<SessionEntity> Sessions => Set<SessionEntity>();
|
||||
public DbSet<IdempotencyKeyEntity> IdempotencyKeys => Set<IdempotencyKeyEntity>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
// Идентификаторы создаёт приложение (Guid.CreateVersion7: монотонные, индексы вставляются «справа»).
|
||||
// Время created_at тоже назначает приложение, а не DEFAULT now(): см. порядок операций отправки сообщения.
|
||||
|
||||
modelBuilder.Entity<UserEntity>(e =>
|
||||
{
|
||||
e.ToTable("users", t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_users_username_format", @"username ~ '^[a-z0-9_]{3,32}$'");
|
||||
t.HasCheckConstraint("ck_users_display_name_not_blank", @"display_name ~ '\S'");
|
||||
});
|
||||
e.HasKey(x => x.Id);
|
||||
e.Property(x => x.Id).ValueGeneratedNever();
|
||||
e.Property(x => x.Username).HasMaxLength(32).IsRequired();
|
||||
e.Property(x => x.DisplayName).HasMaxLength(100).IsRequired(); // varchar(n) считает символы, не байты
|
||||
e.Property(x => x.PasswordHash).IsRequired();
|
||||
e.Property(x => x.CreatedAt).IsRequired();
|
||||
e.HasIndex(x => x.Username).IsUnique().HasDatabaseName("ux_users_username");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ChatEntity>(e =>
|
||||
{
|
||||
e.ToTable("chats", t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_chats_title_not_blank", @"title ~ '\S'");
|
||||
t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
});
|
||||
e.HasKey(x => x.Id);
|
||||
e.Property(x => x.Id).ValueGeneratedNever();
|
||||
e.Property(x => x.Title).HasMaxLength(100).IsRequired();
|
||||
e.Property(x => x.CreatedAt).IsRequired();
|
||||
e.Property(x => x.HistoryVersion).HasDefaultValue(0L).IsRequired();
|
||||
// Список чатов: сортировка по (created_at, id) с keyset-курсором.
|
||||
e.HasIndex(x => new { x.CreatedAt, x.Id }).HasDatabaseName("ix_chats_created_at_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ChatMemberEntity>(e =>
|
||||
{
|
||||
e.ToTable("chat_members");
|
||||
e.HasKey(x => new { x.ChatId, x.UserId }); // один пользователь не может быть в чате дважды
|
||||
e.HasOne<ChatEntity>().WithMany().HasForeignKey(x => x.ChatId).OnDelete(DeleteBehavior.Cascade);
|
||||
e.HasOne<UserEntity>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Restrict);
|
||||
// PK обслуживает «участники чата»; этот индекс — «чаты пользователя» и проверку доступа.
|
||||
e.HasIndex(x => x.UserId).HasDatabaseName("ix_chat_members_user_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<MessageEntity>(e =>
|
||||
{
|
||||
e.ToTable("messages", t =>
|
||||
t.HasCheckConstraint("ck_messages_text_not_blank", @"text ~ '\S'")); // lab2: вложений нет
|
||||
e.HasKey(x => x.Id);
|
||||
e.Property(x => x.Id).ValueGeneratedNever();
|
||||
e.Property(x => x.Text).HasMaxLength(4000).IsRequired();
|
||||
e.Property(x => x.CreatedAt).IsRequired();
|
||||
// Составной FK: отправитель обязан быть участником именно этого чата. Он же гарантирует существование
|
||||
// чата и пользователя, поэтому отдельные FK на chats/users не нужны.
|
||||
e.HasOne<ChatMemberEntity>().WithMany()
|
||||
.HasForeignKey(x => new { x.ChatId, x.SenderId })
|
||||
.HasPrincipalKey(x => new { x.ChatId, x.UserId })
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
// Страница истории: WHERE chat_id = @c AND (created_at, id) > (@t, @i) ORDER BY created_at, id LIMIT n.
|
||||
e.HasIndex(x => new { x.ChatId, x.CreatedAt, x.Id }).HasDatabaseName("ix_messages_chat_history");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<SessionEntity>(e =>
|
||||
{
|
||||
e.ToTable("sessions", t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
});
|
||||
e.HasKey(x => x.Id);
|
||||
e.Property(x => x.Id).ValueGeneratedNever();
|
||||
e.Property(x => x.TokenHash).IsRequired();
|
||||
e.Property(x => x.CreatedAt).IsRequired();
|
||||
e.Property(x => x.ExpiresAt).IsRequired();
|
||||
e.HasOne<UserEntity>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
// Аутентификация каждого запроса: поиск по хешу токена.
|
||||
e.HasIndex(x => x.TokenHash).IsUnique().HasDatabaseName("ux_sessions_token_hash");
|
||||
// Фоновая очистка истёкших сессий.
|
||||
e.HasIndex(x => x.ExpiresAt).HasDatabaseName("ix_sessions_expires_at");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<IdempotencyKeyEntity>(e =>
|
||||
{
|
||||
e.ToTable("idempotency_keys", t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32");
|
||||
t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at");
|
||||
});
|
||||
// PK = область уникальности. Именно его уникальный индекс заставляет конкурентные запросы с одним ключом
|
||||
// ждать друг друга. FK на messages(id) (DEFERRABLE INITIALLY DEFERRED) добавлен в миграции вручную.
|
||||
e.HasKey(x => new { x.UserId, x.ChatId, x.Key });
|
||||
e.Property(x => x.Key).HasMaxLength(128).IsRequired();
|
||||
e.Property(x => x.RequestHash).IsRequired();
|
||||
e.Property(x => x.CreatedAt).IsRequired();
|
||||
e.Property(x => x.ExpiresAt).IsRequired();
|
||||
// Очистка истёкших ключей.
|
||||
e.HasIndex(x => x.ExpiresAt).HasDatabaseName("ix_idempotency_keys_expires_at");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(MessengerDbContext))]
|
||||
[Migration("20261023140810_InitialSchema")]
|
||||
partial class InitialSchema
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("HistoryVersion")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint")
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnName("history_version");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_chats");
|
||||
|
||||
b.HasIndex("CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_chats_created_at_id");
|
||||
|
||||
b.ToTable("chats", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
|
||||
t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("ChatId", "UserId")
|
||||
.HasName("pk_chat_members");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_chat_members_user_id");
|
||||
|
||||
b.ToTable("chat_members", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<Guid>("SenderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("sender_id");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("character varying(4000)")
|
||||
.HasColumnName("text");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_messages");
|
||||
|
||||
b.HasIndex("ChatId", "SenderId")
|
||||
.HasDatabaseName("ix_messages_chat_id_sender_id");
|
||||
|
||||
b.HasIndex("ChatId", "CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_messages_chat_history");
|
||||
|
||||
b.ToTable("messages", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<byte[]>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("token_hash");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_sessions");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_sessions_expires_at");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_sessions_token_hash");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_sessions_user_id");
|
||||
|
||||
b.ToTable("sessions", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("display_name");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("password_hash");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_users");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_users_username");
|
||||
|
||||
b.ToTable("users", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'");
|
||||
|
||||
t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_chats_chat_id");
|
||||
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_users_user_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatMemberEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId", "SenderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_messages_chat_members_chat_id_sender_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_sessions_users_user_id");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialSchema : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "chats",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
title = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
history_version = table.Column<long>(type: "bigint", nullable: false, defaultValue: 0L)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_chats", x => x.id);
|
||||
table.CheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
table.CheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'");
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "users",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
username = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
display_name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
password_hash = table.Column<string>(type: "text", nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_users", x => x.id);
|
||||
table.CheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'");
|
||||
table.CheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'");
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "chat_members",
|
||||
columns: table => new
|
||||
{
|
||||
chat_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
user_id = table.Column<Guid>(type: "uuid", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_chat_members", x => new { x.chat_id, x.user_id });
|
||||
table.ForeignKey(
|
||||
name: "fk_chat_members_chats_chat_id",
|
||||
column: x => x.chat_id,
|
||||
principalTable: "chats",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "fk_chat_members_users_user_id",
|
||||
column: x => x.user_id,
|
||||
principalTable: "users",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "sessions",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
token_hash = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||
user_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
revoked_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_sessions", x => x.id);
|
||||
table.CheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
table.CheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
table.ForeignKey(
|
||||
name: "fk_sessions_users_user_id",
|
||||
column: x => x.user_id,
|
||||
principalTable: "users",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "messages",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
chat_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
sender_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
text = table.Column<string>(type: "character varying(4000)", maxLength: 4000, nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_messages", x => x.id);
|
||||
table.CheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'");
|
||||
table.ForeignKey(
|
||||
name: "fk_messages_chat_members_chat_id_sender_id",
|
||||
columns: x => new { x.chat_id, x.sender_id },
|
||||
principalTable: "chat_members",
|
||||
principalColumns: new[] { "chat_id", "user_id" },
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_chat_members_user_id",
|
||||
table: "chat_members",
|
||||
column: "user_id");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_chats_created_at_id",
|
||||
table: "chats",
|
||||
columns: new[] { "created_at", "id" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_messages_chat_history",
|
||||
table: "messages",
|
||||
columns: new[] { "chat_id", "created_at", "id" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_messages_chat_id_sender_id",
|
||||
table: "messages",
|
||||
columns: new[] { "chat_id", "sender_id" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_sessions_expires_at",
|
||||
table: "sessions",
|
||||
column: "expires_at");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_sessions_user_id",
|
||||
table: "sessions",
|
||||
column: "user_id");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ux_sessions_token_hash",
|
||||
table: "sessions",
|
||||
column: "token_hash",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ux_users_username",
|
||||
table: "users",
|
||||
column: "username",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "messages");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "sessions");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "chat_members");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "chats");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "users");
|
||||
}
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(MessengerDbContext))]
|
||||
[Migration("20261023170730_AddChatLastMessageAt")]
|
||||
partial class AddChatLastMessageAt
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("HistoryVersion")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint")
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnName("history_version");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastMessageAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_message_at");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_chats");
|
||||
|
||||
b.HasIndex("CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_chats_created_at_id");
|
||||
|
||||
b.ToTable("chats", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
|
||||
t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("ChatId", "UserId")
|
||||
.HasName("pk_chat_members");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_chat_members_user_id");
|
||||
|
||||
b.ToTable("chat_members", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<Guid>("SenderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("sender_id");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("character varying(4000)")
|
||||
.HasColumnName("text");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_messages");
|
||||
|
||||
b.HasIndex("ChatId", "SenderId")
|
||||
.HasDatabaseName("ix_messages_chat_id_sender_id");
|
||||
|
||||
b.HasIndex("ChatId", "CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_messages_chat_history");
|
||||
|
||||
b.ToTable("messages", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<byte[]>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("token_hash");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_sessions");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_sessions_expires_at");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_sessions_token_hash");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_sessions_user_id");
|
||||
|
||||
b.ToTable("sessions", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("display_name");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("password_hash");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_users");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_users_username");
|
||||
|
||||
b.ToTable("users", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'");
|
||||
|
||||
t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_chats_chat_id");
|
||||
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_users_user_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatMemberEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId", "SenderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_messages_chat_members_chat_id_sender_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_sessions_users_user_id");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddChatLastMessageAt : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "last_message_at",
|
||||
table: "chats",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "last_message_at",
|
||||
table: "chats");
|
||||
}
|
||||
}
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(MessengerDbContext))]
|
||||
[Migration("20261106145724_AddIdempotencyKeys")]
|
||||
partial class AddIdempotencyKeys
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("HistoryVersion")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint")
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnName("history_version");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastMessageAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_message_at");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_chats");
|
||||
|
||||
b.HasIndex("CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_chats_created_at_id");
|
||||
|
||||
b.ToTable("chats", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
|
||||
t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("ChatId", "UserId")
|
||||
.HasName("pk_chat_members");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_chat_members_user_id");
|
||||
|
||||
b.ToTable("chat_members", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("message_id");
|
||||
|
||||
b.Property<byte[]>("RequestHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("request_hash");
|
||||
|
||||
b.HasKey("UserId", "ChatId", "Key")
|
||||
.HasName("pk_idempotency_keys");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_idempotency_keys_expires_at");
|
||||
|
||||
b.ToTable("idempotency_keys", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<Guid>("SenderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("sender_id");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("character varying(4000)")
|
||||
.HasColumnName("text");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_messages");
|
||||
|
||||
b.HasIndex("ChatId", "SenderId")
|
||||
.HasDatabaseName("ix_messages_chat_id_sender_id");
|
||||
|
||||
b.HasIndex("ChatId", "CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_messages_chat_history");
|
||||
|
||||
b.ToTable("messages", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<byte[]>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("token_hash");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_sessions");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_sessions_expires_at");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_sessions_token_hash");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_sessions_user_id");
|
||||
|
||||
b.ToTable("sessions", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("display_name");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("password_hash");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_users");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_users_username");
|
||||
|
||||
b.ToTable("users", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'");
|
||||
|
||||
t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_chats_chat_id");
|
||||
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_users_user_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatMemberEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId", "SenderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_messages_chat_members_chat_id_sender_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_sessions_users_user_id");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddIdempotencyKeys : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "idempotency_keys",
|
||||
columns: table => new
|
||||
{
|
||||
user_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
chat_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
key = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
request_hash = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||
message_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_idempotency_keys", x => new { x.user_id, x.chat_id, x.key });
|
||||
table.CheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at");
|
||||
table.CheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32");
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "ix_idempotency_keys_expires_at",
|
||||
table: "idempotency_keys",
|
||||
column: "expires_at");
|
||||
|
||||
// Ключ идемпотентности вставляется РАНЬШЕ сообщения (claim → резервирование слота → вставка), поэтому FK
|
||||
// проверяется при COMMIT (DEFERRABLE INITIALLY DEFERRED): запись «ключ → сообщение» без сообщения не переживёт транзакцию.
|
||||
// Миграция только добавляет таблицу: запущенная предыдущая версия API её не использует и продолжает работать
|
||||
// (совместимость для rolling update).
|
||||
migrationBuilder.Sql("""
|
||||
ALTER TABLE idempotency_keys
|
||||
ADD CONSTRAINT fk_idempotency_keys_messages_message_id
|
||||
FOREIGN KEY (message_id) REFERENCES messages (id) ON DELETE CASCADE
|
||||
DEFERRABLE INITIALLY DEFERRED;
|
||||
""");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "idempotency_keys");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Messenger.Api.Data.Migrations
|
||||
{
|
||||
[DbContext(typeof(MessengerDbContext))]
|
||||
partial class MessengerDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("HistoryVersion")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint")
|
||||
.HasDefaultValue(0L)
|
||||
.HasColumnName("history_version");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastMessageAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_message_at");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_chats");
|
||||
|
||||
b.HasIndex("CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_chats_created_at_id");
|
||||
|
||||
b.ToTable("chats", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0");
|
||||
|
||||
t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("ChatId", "UserId")
|
||||
.HasName("pk_chat_members");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_chat_members_user_id");
|
||||
|
||||
b.ToTable("chat_members", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("message_id");
|
||||
|
||||
b.Property<byte[]>("RequestHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("request_hash");
|
||||
|
||||
b.HasKey("UserId", "ChatId", "Key")
|
||||
.HasName("pk_idempotency_keys");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_idempotency_keys_expires_at");
|
||||
|
||||
b.ToTable("idempotency_keys", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("ChatId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("chat_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<Guid>("SenderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("sender_id");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("character varying(4000)")
|
||||
.HasColumnName("text");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_messages");
|
||||
|
||||
b.HasIndex("ChatId", "SenderId")
|
||||
.HasDatabaseName("ix_messages_chat_id_sender_id");
|
||||
|
||||
b.HasIndex("ChatId", "CreatedAt", "Id")
|
||||
.HasDatabaseName("ix_messages_chat_history");
|
||||
|
||||
b.ToTable("messages", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<byte[]>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("token_hash");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("user_id");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_sessions");
|
||||
|
||||
b.HasIndex("ExpiresAt")
|
||||
.HasDatabaseName("ix_sessions_expires_at");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_sessions_token_hash");
|
||||
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("ix_sessions_user_id");
|
||||
|
||||
b.ToTable("sessions", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at");
|
||||
|
||||
t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("display_name");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("password_hash");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_users");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_users_username");
|
||||
|
||||
b.ToTable("users", null, t =>
|
||||
{
|
||||
t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'");
|
||||
|
||||
t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_chats_chat_id");
|
||||
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_chat_members_users_user_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.ChatMemberEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ChatId", "SenderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_messages_chat_members_chat_id_sender_id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b =>
|
||||
{
|
||||
b.HasOne("Messenger.Api.Data.UserEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_sessions_users_user_id");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using System.Text;
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Models;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
private const string BasicChallenge = "Basic realm=\"messenger\", charset=\"UTF-8\"";
|
||||
|
||||
public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost("/api/v1/auth/sessions", CreateSession);
|
||||
endpoints.MapDelete("/api/v1/auth/sessions/current", RevokeCurrentSession).RequireAuthorization();
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateSession(
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
IPasswordHasher hasher,
|
||||
AuthSessionOptions options,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// Любая проблема с заголовком или credentials даёт один и тот же ответ.
|
||||
var unauthorized = () => ApiErrors.Unauthorized(httpContext, BasicChallenge, "Неверное имя пользователя или пароль");
|
||||
|
||||
if (!TryParseBasic(httpContext.Request, out var username, out var password))
|
||||
{
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
var user = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Username == username, ct);
|
||||
|
||||
// Проверка выполняется и для несуществующего пользователя (null → заглушка), чтобы время ответа
|
||||
// не выдавало, существует ли username.
|
||||
bool passwordOk;
|
||||
try
|
||||
{
|
||||
passwordOk = await hasher.VerifyAsync(user?.PasswordHash, password, ct);
|
||||
}
|
||||
catch (PasswordHasherBusyException)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 503, "unavailable", "Сервис временно перегружен, повторите запрос позже");
|
||||
}
|
||||
|
||||
if (user is null || !passwordOk)
|
||||
{
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
var token = SessionTokens.Generate();
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
var session = new SessionEntity
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
TokenHash = SessionTokens.Hash(token),
|
||||
UserId = user.Id,
|
||||
CreatedAt = now,
|
||||
ExpiresAt = now + options.Ttl
|
||||
};
|
||||
|
||||
db.Sessions.Add(session);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// Ответ с токеном нельзя кэшировать промежуточными узлами.
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
|
||||
return Results.Json(
|
||||
new SessionResponse(
|
||||
token,
|
||||
"Bearer",
|
||||
session.ExpiresAt,
|
||||
new User
|
||||
{
|
||||
Id = user.Id,
|
||||
Username = user.Username,
|
||||
DisplayName = user.DisplayName,
|
||||
CreatedAt = user.CreatedAt
|
||||
}),
|
||||
statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> RevokeCurrentSession(
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var sessionId = httpContext.GetSessionId();
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
|
||||
// Один UPDATE с условием: отзыв атомарен даже при двух параллельных DELETE с одним токеном.
|
||||
var revoked = await db.Sessions
|
||||
.Where(s => s.Id == sessionId && s.RevokedAt == null)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(x => x.RevokedAt, now), ct);
|
||||
|
||||
return revoked == 0
|
||||
? ApiErrors.Unauthorized(httpContext, BearerAuth.Challenge, "Требуется действительный Bearer-токен")
|
||||
: Results.NoContent();
|
||||
}
|
||||
|
||||
// Basic: base64("username:password"), разделитель — ПЕРВОЕ двоеточие (в пароле двоеточие допустимо).
|
||||
// Всё, что не разбирается строго (схема, base64, UTF-8, формат), считается неверными credentials.
|
||||
private static bool TryParseBasic(HttpRequest request, out string username, out string password)
|
||||
{
|
||||
username = password = string.Empty;
|
||||
|
||||
if (request.Headers.Authorization.Count != 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var header = request.Headers.Authorization[0];
|
||||
const string prefix = "Basic ";
|
||||
if (header is null || !header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string decoded;
|
||||
try
|
||||
{
|
||||
var bytes = Convert.FromBase64String(header[prefix.Length..].Trim());
|
||||
decoded = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(bytes);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or DecoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var separator = decoded.IndexOf(':');
|
||||
if (separator <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
username = decoded[..separator];
|
||||
password = decoded[(separator + 1)..];
|
||||
|
||||
// Username по контракту — ASCII [a-z0-9_]{3,32}; пароль — 12..128 code points. Отсекаем до дорогого Argon2.
|
||||
var length = ApiErrors.CodePoints(password);
|
||||
return username.Length is >= 3 and <= 32 && length is >= 12 and <= 128;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Models;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class ChatEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapChatEndpoints(
|
||||
this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost("/api/v1/chats", CreateChat).RequireAuthorization();
|
||||
endpoints.MapGet("/api/v1/chats", ListChats).RequireAuthorization();
|
||||
endpoints.MapGet("/api/v1/chats/{chatId}", GetChat).RequireAuthorization();
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateChat(
|
||||
CreateChatRequest request,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.Title) ||
|
||||
ApiErrors.CodePoints(request.Title) > 100 ||
|
||||
request.MemberIds.Count is < 1 or > 100 ||
|
||||
request.MemberIds.Distinct().Count() != request.MemberIds.Count)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные данные чата");
|
||||
}
|
||||
|
||||
if (!request.MemberIds.Contains(userId))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Создатель должен быть участником чата");
|
||||
}
|
||||
|
||||
var knownMembers = await db.Users.CountAsync(u => request.MemberIds.Contains(u.Id), ct);
|
||||
if (knownMembers != request.MemberIds.Count)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Неизвестный участник чата");
|
||||
}
|
||||
|
||||
var chat = new ChatEntity
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Title = request.Title,
|
||||
CreatedAt = Timestamps.UtcNowMilliseconds()
|
||||
};
|
||||
|
||||
// Чат и все его участники сохраняются одним SaveChanges, то есть одной транзакцией:
|
||||
// либо создано всё, либо ничего (нет чата без участников).
|
||||
db.Chats.Add(chat);
|
||||
db.ChatMembers.AddRange(request.MemberIds.Select(id => new ChatMemberEntity { ChatId = chat.Id, UserId = id }));
|
||||
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.ForeignKeyViolation })
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Неизвестный участник чата");
|
||||
}
|
||||
|
||||
return Results.Created($"/api/v1/chats/{chat.Id}", ToDto(chat, request.MemberIds.Order().ToList()));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListChats(
|
||||
int? limit,
|
||||
string? cursor,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
var pageSize = limit ?? 50;
|
||||
|
||||
if (pageSize is < 1 or > 100 || !Cursors.TryDecode(cursor, Cursors.Chats, out var after))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные параметры пагинации");
|
||||
}
|
||||
|
||||
// Keyset: строковое сравнение (created_at, id) > (курсор), без OFFSET и без просмотра всей выдачи.
|
||||
IQueryable<ChatEntity> source = after is null
|
||||
? db.Chats.FromSql($"""
|
||||
SELECT c.* FROM chats c
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = {userId})
|
||||
""")
|
||||
: db.Chats.FromSql($"""
|
||||
SELECT c.* FROM chats c
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = {userId})
|
||||
AND (c.created_at, c.id) > ({after.Value.CreatedAt}, {after.Value.Id})
|
||||
""");
|
||||
|
||||
var chats = await source
|
||||
.AsNoTracking()
|
||||
.OrderBy(c => c.CreatedAt).ThenBy(c => c.Id)
|
||||
.Take(pageSize + 1)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var hasNext = chats.Count > pageSize;
|
||||
if (hasNext)
|
||||
{
|
||||
chats.RemoveAt(chats.Count - 1);
|
||||
}
|
||||
|
||||
var ids = chats.Select(c => c.Id).ToList();
|
||||
var members = (await db.ChatMembers
|
||||
.AsNoTracking()
|
||||
.Where(m => ids.Contains(m.ChatId))
|
||||
.Select(m => new { m.ChatId, m.UserId })
|
||||
.ToListAsync(ct))
|
||||
.ToLookup(m => m.ChatId, m => m.UserId);
|
||||
|
||||
var items = chats.Select(c => ToDto(c, members[c.Id].Order().ToList())).ToList();
|
||||
var nextCursor = hasNext ? Cursors.Encode(Cursors.Chats, chats[^1].CreatedAt, chats[^1].Id) : null;
|
||||
|
||||
return Results.Ok(new { items, next_cursor = nextCursor });
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetChat(
|
||||
Guid chatId,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
|
||||
// Отсутствующий и чужой чат неразличимы: оба дают 404.
|
||||
var chat = await db.Chats
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(c => c.Id == chatId && db.ChatMembers.Any(m => m.ChatId == c.Id && m.UserId == userId), ct);
|
||||
|
||||
if (chat is null)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден");
|
||||
}
|
||||
|
||||
var memberIds = await db.ChatMembers
|
||||
.AsNoTracking()
|
||||
.Where(m => m.ChatId == chatId)
|
||||
.Select(m => m.UserId)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return Results.Ok(ToDto(chat, memberIds.Order().ToList()));
|
||||
}
|
||||
|
||||
private static Chat ToDto(ChatEntity chat, List<Guid> memberIds) => new()
|
||||
{
|
||||
Id = chat.Id,
|
||||
Title = chat.Title,
|
||||
MemberIds = memberIds,
|
||||
CreatedAt = chat.CreatedAt
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Models;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class MessageEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapMessageEndpoints(
|
||||
this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost("/api/v1/chats/{chatId}/messages", CreateMessage).RequireAuthorization();
|
||||
endpoints.MapGet("/api/v1/chats/{chatId}/messages", ListMessages).RequireAuthorization();
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateMessage(
|
||||
Guid chatId,
|
||||
CreateMessageRequest request,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
IdempotencySettings idempotency,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
|
||||
// Сначала доступ к ресурсу (404 для постороннего), затем валидация ключа и тела. Доступ проверяется при каждом
|
||||
// запросе, в том числе при повторе с тем же Idempotency-Key.
|
||||
if (!await IsMemberAsync(db, chatId, userId, ct))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден");
|
||||
}
|
||||
|
||||
var key = IdempotencyKeys.ReadKey(httpContext.Request);
|
||||
if (key is null)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Требуется заголовок Idempotency-Key ([A-Za-z0-9._:-], 1-128 символов)");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.Text) || ApiErrors.CodePoints(request.Text) > 4000)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный текст сообщения");
|
||||
}
|
||||
|
||||
// Транзакция: (0) claim ключа идемпотентности, (1) UPDATE чата берёт блокировку его строки и выдаёт created_at,
|
||||
// (2) INSERT сообщения, (3) COMMIT. Записи в один чат идут строго по очереди, поэтому порядок коммитов совпадает
|
||||
// с порядком (created_at, id) и курсор не может «проскочить» сообщение, закоммиченное позже. Версия истории
|
||||
// растёт в той же транзакции. Ключ и сообщение коммитятся вместе: при любой ошибке откатывается и то и другое,
|
||||
// поэтому 5xx не «запоминается» как результат, а клиент может безопасно повторить запрос с тем же ключом.
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
|
||||
var messageId = Guid.CreateVersion7();
|
||||
var (claim, storedMessageId) = await IdempotencyKeys.ClaimAsync(
|
||||
db, tx, userId, chatId, key, IdempotencyKeys.RequestHash(request.Text), messageId, idempotency.Ttl, ct);
|
||||
|
||||
if (claim == ClaimResult.Conflict)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 409, "conflict", "Idempotency-Key уже использован с другим сообщением");
|
||||
}
|
||||
|
||||
if (claim == ClaimResult.Replay)
|
||||
{
|
||||
// Повтор: ничего не пишем, возвращаем то же сообщение и тот же код 201.
|
||||
var original = await db.Messages.AsNoTracking().FirstAsync(m => m.Id == storedMessageId, ct);
|
||||
return Results.Created($"/api/v1/chats/{chatId}/messages", ToDto(original));
|
||||
}
|
||||
|
||||
var createdAt = await ReserveMessageSlotAsync(db, tx, chatId, userId, ct);
|
||||
if (createdAt is null)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден");
|
||||
}
|
||||
|
||||
var message = new MessageEntity
|
||||
{
|
||||
Id = messageId,
|
||||
ChatId = chatId,
|
||||
SenderId = userId,
|
||||
Text = request.Text,
|
||||
CreatedAt = createdAt.Value
|
||||
};
|
||||
|
||||
db.Messages.Add(message);
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.CheckViolation })
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный текст сообщения");
|
||||
}
|
||||
|
||||
await tx.CommitAsync(ct);
|
||||
|
||||
return Results.Created($"/api/v1/chats/{chatId}/messages", ToDto(message));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListMessages(
|
||||
Guid chatId,
|
||||
int? limit,
|
||||
string? cursor,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
IMessageHistoryCache cache,
|
||||
DiagnosticsSettings diagnostics,
|
||||
IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions> jsonOptions,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
var pageSize = limit ?? 50;
|
||||
|
||||
// Один запрос проверяет доступ (null → 404) и читает актуальную версию истории из PostgreSQL.
|
||||
// Версия берётся из БД при каждом чтении, а не из кэша: после подтверждённой записи ключ гарантированно новый.
|
||||
var version = await db.Chats
|
||||
.AsNoTracking()
|
||||
.Where(c => c.Id == chatId && db.ChatMembers.Any(m => m.ChatId == c.Id && m.UserId == userId))
|
||||
.Select(c => (long?)c.HistoryVersion)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
if (version is null)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден");
|
||||
}
|
||||
|
||||
if (pageSize is < 1 or > 100 || !Cursors.TryDecode(cursor, Cursors.Messages(chatId), out var after))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные параметры пагинации");
|
||||
}
|
||||
|
||||
// Ключ = чат + версия истории + размер страницы + курсор. Страница под этим ключом никогда не устаревает:
|
||||
// любая запись увеличивает версию, и читатели переходят на другой ключ.
|
||||
var key = $"hist:{chatId:N}:v{version}:l{pageSize}:{cursor ?? "-"}";
|
||||
|
||||
var (cached, status) = await cache.GetAsync(key, ct);
|
||||
if (cached is not null)
|
||||
{
|
||||
return CachedJson(httpContext, diagnostics, cached, status);
|
||||
}
|
||||
|
||||
// Keyset по индексу (chat_id, created_at, id): читается только страница, а не вся история.
|
||||
IQueryable<MessageEntity> source = after is null
|
||||
? db.Messages.FromSql($"SELECT * FROM messages WHERE chat_id = {chatId}")
|
||||
: db.Messages.FromSql($"""
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = {chatId} AND (created_at, id) > ({after.Value.CreatedAt}, {after.Value.Id})
|
||||
""");
|
||||
|
||||
var messages = await source
|
||||
.AsNoTracking()
|
||||
.OrderBy(m => m.CreatedAt).ThenBy(m => m.Id)
|
||||
.Take(pageSize + 1)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var hasNext = messages.Count > pageSize;
|
||||
if (hasNext)
|
||||
{
|
||||
messages.RemoveAt(messages.Count - 1);
|
||||
}
|
||||
|
||||
var nextCursor = hasNext
|
||||
? Cursors.Encode(Cursors.Messages(chatId), messages[^1].CreatedAt, messages[^1].Id)
|
||||
: null;
|
||||
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(
|
||||
new { items = messages.Select(ToDto).ToList(), next_cursor = nextCursor },
|
||||
jsonOptions.Value.SerializerOptions);
|
||||
|
||||
await cache.SetAsync(key, json, ct);
|
||||
return CachedJson(httpContext, diagnostics, json, status);
|
||||
}
|
||||
|
||||
// Ответ из кэша и ответ из БД байт-в-байт одинаковы: сериализуется одна и та же структура теми же настройками.
|
||||
private static IResult CachedJson(HttpContext context, DiagnosticsSettings diagnostics, string json, CacheStatus status)
|
||||
{
|
||||
if (diagnostics.Headers)
|
||||
{
|
||||
context.Response.Headers["X-Cache"] = status.ToString().ToLowerInvariant();
|
||||
}
|
||||
|
||||
return Results.Content(json, "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
private static Task<bool> IsMemberAsync(MessengerDbContext db, Guid chatId, Guid userId, CancellationToken ct) =>
|
||||
db.ChatMembers.AnyAsync(m => m.ChatId == chatId && m.UserId == userId, ct);
|
||||
|
||||
// Атомарно: проверяет членство, увеличивает версию истории и возвращает created_at нового сообщения —
|
||||
// строго больше времени предыдущего (даже при откате системных часов или двух сообщениях в одну миллисекунду).
|
||||
// null — чата нет или пользователь не участник.
|
||||
private static async Task<DateTimeOffset?> ReserveMessageSlotAsync(
|
||||
MessengerDbContext db,
|
||||
IDbContextTransaction tx,
|
||||
Guid chatId,
|
||||
Guid userId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var connection = (NpgsqlConnection)db.Database.GetDbConnection();
|
||||
await using var command = new NpgsqlCommand("""
|
||||
UPDATE chats c
|
||||
SET history_version = c.history_version + 1,
|
||||
last_message_at = GREATEST(@now, COALESCE(c.last_message_at + interval '1 millisecond', @now))
|
||||
WHERE c.id = @chat
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = @user)
|
||||
RETURNING c.last_message_at
|
||||
""", connection, (NpgsqlTransaction)tx.GetDbTransaction());
|
||||
|
||||
command.Parameters.AddWithValue("now", Timestamps.UtcNowMilliseconds());
|
||||
command.Parameters.AddWithValue("chat", chatId);
|
||||
command.Parameters.AddWithValue("user", userId);
|
||||
|
||||
await using var reader = await command.ExecuteReaderAsync(ct);
|
||||
return await reader.ReadAsync(ct) ? reader.GetFieldValue<DateTimeOffset>(0) : null;
|
||||
}
|
||||
|
||||
private static Message ToDto(MessageEntity m) => new()
|
||||
{
|
||||
Id = m.Id,
|
||||
ChatId = m.ChatId,
|
||||
SenderId = m.SenderId,
|
||||
Text = m.Text,
|
||||
CreatedAt = m.CreatedAt
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Messenger.Api.Models;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Messenger.Api.Data;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class UserEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapUserEndpoints(
|
||||
this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost(
|
||||
"/api/v1/users",
|
||||
CreateUser);
|
||||
|
||||
endpoints.MapGet(
|
||||
"/api/v1/users/me",
|
||||
GetCurrentUser).RequireAuthorization();
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateUser(
|
||||
CreateUserRequest request,
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
IPasswordHasher hasher,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (!Regex.IsMatch(request.Username, @"\A[a-z0-9_]{3,32}\z"))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный username");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.DisplayName) ||
|
||||
ApiErrors.CodePoints(request.DisplayName) > 100)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "display_name должен содержать от 1 до 100 символов");
|
||||
}
|
||||
|
||||
var passwordLength = ApiErrors.CodePoints(request.Password);
|
||||
if (passwordLength < 12 || passwordLength > 128)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 400, "invalid_request", "Пароль должен содержать от 12 до 128 символов");
|
||||
}
|
||||
|
||||
// Быстрый отказ, чтобы не тратить дорогой Argon2 на заведомо занятый username.
|
||||
// Это только оптимизация: от гонки защищает уникальный индекс (см. catch ниже).
|
||||
if (await db.Users.AnyAsync(u => u.Username == request.Username, ct))
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 409, "conflict", "Username уже занят");
|
||||
}
|
||||
|
||||
// Хеш считается до SaveChanges: соединение с БД не простаивает на CPU-работе.
|
||||
string passwordHash;
|
||||
try
|
||||
{
|
||||
passwordHash = await hasher.HashAsync(request.Password, ct);
|
||||
}
|
||||
catch (PasswordHasherBusyException)
|
||||
{
|
||||
return ApiErrors.Error(httpContext, 503, "unavailable", "Сервис временно перегружен, повторите запрос позже");
|
||||
}
|
||||
|
||||
var entity = new UserEntity
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Username = request.Username,
|
||||
DisplayName = request.DisplayName,
|
||||
PasswordHash = passwordHash,
|
||||
CreatedAt = Timestamps.UtcNowMilliseconds()
|
||||
};
|
||||
|
||||
db.Users.Add(entity);
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (DbUpdateException ex) when (
|
||||
ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: "ux_users_username" })
|
||||
{
|
||||
// Параллельный запрос с тем же username успел раньше проверки AnyAsync.
|
||||
return ApiErrors.Error(httpContext, 409, "conflict", "Username уже занят");
|
||||
}
|
||||
|
||||
// В ответ уходит API-модель без password_hash, а не сущность таблицы.
|
||||
var user = new User
|
||||
{
|
||||
Id = entity.Id,
|
||||
Username = entity.Username,
|
||||
DisplayName = entity.DisplayName,
|
||||
CreatedAt = entity.CreatedAt
|
||||
};
|
||||
|
||||
return Results.Created($"/api/v1/users/{user.Id}", user);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetCurrentUser(
|
||||
HttpContext httpContext,
|
||||
MessengerDbContext db,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var userId = httpContext.GetUserId();
|
||||
|
||||
var user = await db.Users
|
||||
.AsNoTracking()
|
||||
.Where(u => u.Id == userId)
|
||||
.Select(u => new User
|
||||
{
|
||||
Id = u.Id,
|
||||
Username = u.Username,
|
||||
DisplayName = u.DisplayName,
|
||||
CreatedAt = u.CreatedAt
|
||||
})
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
// Сессия ссылается на пользователя внешним ключом, поэтому null здесь невозможен; ответ всё равно безопасный.
|
||||
return user is null
|
||||
? ApiErrors.Unauthorized(httpContext, BearerAuth.Challenge, "Требуется действительный Bearer-токен")
|
||||
: Results.Ok(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Services\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EFCore.NamingConventions" Version="10.0.1" />
|
||||
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.13" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="3.4.20" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Models
|
||||
{
|
||||
public sealed class Chat
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public string Title { get; init; } = String.Empty;
|
||||
public List<Guid> MemberIds { get; init; } = new List<Guid>();
|
||||
public DateTimeOffset CreatedAt { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Messenger.Api.Models
|
||||
{
|
||||
public sealed record CreateChatRequest(
|
||||
[property: System.Text.Json.Serialization.JsonRequired] string Title,
|
||||
[property: System.Text.Json.Serialization.JsonRequired] List<Guid> MemberIds);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Models;
|
||||
|
||||
public sealed record CreateMessageRequest([property: System.Text.Json.Serialization.JsonRequired] string Text);
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Models
|
||||
{
|
||||
public sealed record CreateUserRequest(
|
||||
[property: System.Text.Json.Serialization.JsonRequired] string Username,
|
||||
[property: System.Text.Json.Serialization.JsonRequired] string DisplayName,
|
||||
[property: System.Text.Json.Serialization.JsonRequired] string Password);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Models
|
||||
{
|
||||
public sealed class Message
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public Guid ChatId { get; init; }
|
||||
public Guid SenderId { get; init; }
|
||||
public string Text { get; init; } = String.Empty;
|
||||
public DateTimeOffset CreatedAt { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Messenger.Api.Models;
|
||||
|
||||
public sealed record SessionResponse(
|
||||
string Token,
|
||||
string TokenType,
|
||||
DateTimeOffset ExpiresAt,
|
||||
User User);
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Models
|
||||
{
|
||||
public sealed class User
|
||||
{
|
||||
public Guid Id { get; init; }
|
||||
public string Username { get; init; } = string.Empty;
|
||||
public string DisplayName { get; init; } = string.Empty;
|
||||
public DateTimeOffset CreatedAt { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
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: сначала drain (SHUTDOWN_DRAIN_SECONDS, /health/ready → 503, запросы ещё принимаются), затем слушатель
|
||||
// закрывается и активные запросы получают не более 5 секунд. Итого < 10 секунд (лимит задания) и < stop_grace_period.
|
||||
builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(5));
|
||||
|
||||
// Настройки читаются лениво из 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.AddSingleton(sp => InstanceSettings.From(sp.GetRequiredService<IConfiguration>()));
|
||||
builder.Services.AddSingleton(sp => IdempotencySettings.From(sp.GetRequiredService<IConfiguration>()));
|
||||
builder.Services.AddSingleton<ShutdownState>();
|
||||
builder.Services.AddHostedService<IdempotencyCleaner>();
|
||||
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(sp => PasswordHashingSettings.From(sp.GetRequiredService<IConfiguration>()));
|
||||
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();
|
||||
|
||||
// Режим one-shot миграции (`dotnet Messenger.Api.dll --migrate`): отдельный контейнер применяет схему и завершается.
|
||||
// API-реплики схему не меняют, поэтому одновременный старт N реплик не создаёт гонку миграций.
|
||||
if (args.Contains("--migrate"))
|
||||
{
|
||||
using var migrationScope = app.Services.CreateScope();
|
||||
migrationScope.ServiceProvider.GetRequiredService<MessengerDbContext>().Database.Migrate();
|
||||
app.Logger.LogInformation("Migrations applied");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Только для локального запуска и тестов (MIGRATE_ON_START=true); в Compose выключено.
|
||||
if (app.Services.GetRequiredService<InstanceSettings>().MigrateOnStart)
|
||||
{
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
// X-Instance-Id в каждом ответе API (включая ошибки и health). Заголовок ставится в OnStarting: UseExceptionHandler
|
||||
// очищает заголовки, а этот обратный вызов срабатывает уже после очистки, перед отправкой ответа.
|
||||
var instanceId = app.Services.GetRequiredService<InstanceSettings>().InstanceId;
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
context.Response.OnStarting(() =>
|
||||
{
|
||||
context.Response.Headers["X-Instance-Id"] = instanceId;
|
||||
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 (сессии, данные, ключи
|
||||
// идемпотентности). Valkey не критичен: без него чтение идёт напрямую из PostgreSQL. После SIGTERM — всегда 503:
|
||||
// балансировщик выводит экземпляр из ротации ещё до закрытия слушателя. Таймаут проверки (1 с) меньше таймаута
|
||||
// проверки в HAProxy (2 с), чтобы зависшая БД давала явный 503, а не обрыв проверки.
|
||||
app.MapGet("/health/ready", async (HttpContext context, MessengerDbContext db, ShutdownState shutdown) =>
|
||||
{
|
||||
if (shutdown.Draining)
|
||||
{
|
||||
return ApiErrors.Error(context, 503, "unavailable", "Экземпляр останавливается");
|
||||
}
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(1));
|
||||
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 (instance {InstanceId}, version {Version})",
|
||||
instanceId, Environment.GetEnvironmentVariable("APP_VERSION") ?? "dev"));
|
||||
// ApplicationStopping выполняется синхронно ДО остановки Kestrel: пока этот обработчик спит, слушатель ещё открыт,
|
||||
// а /health/ready уже отвечает 503. Так балансировщик (inter 1s, fall 2) успевает убрать экземпляр до обрыва соединений.
|
||||
app.Lifetime.ApplicationStopping.Register(() =>
|
||||
{
|
||||
var shutdown = app.Services.GetRequiredService<ShutdownState>();
|
||||
var drain = app.Services.GetRequiredService<InstanceSettings>().DrainDelay;
|
||||
shutdown.StartDraining();
|
||||
app.Logger.LogInformation("SIGTERM received: readiness=503, draining {Seconds} s, then the listener closes", drain.TotalSeconds);
|
||||
if (drain > TimeSpan.Zero)
|
||||
{
|
||||
Thread.Sleep(drain);
|
||||
}
|
||||
});
|
||||
app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Messenger API stopped"));
|
||||
|
||||
app.Run();
|
||||
return 0;
|
||||
|
||||
// Делает Program доступным для WebApplicationFactory<Program> в тестах.
|
||||
public partial class Program { }
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5015",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:7165;http://localhost:5015",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class ApiErrors
|
||||
{
|
||||
public static int CodePoints(string value) => value.EnumerateRunes().Count();
|
||||
|
||||
// 401 с обязательным заголовком WWW-Authenticate (контракт: Basic для входа, Bearer для остального API).
|
||||
public static IResult Unauthorized(HttpContext context, string challenge, string message)
|
||||
{
|
||||
context.Response.Headers.WWWAuthenticate = challenge;
|
||||
return Error(context, 401, "unauthorized", message);
|
||||
}
|
||||
|
||||
public static IResult Error(
|
||||
HttpContext context,
|
||||
int statusCode,
|
||||
string code,
|
||||
string message)
|
||||
{
|
||||
var requestId = context.Items["request_id"]?.ToString() ?? context.TraceIdentifier;
|
||||
|
||||
// UseExceptionHandler очищает заголовки ответа, поэтому выставляем X-Request-Id заново.
|
||||
context.Response.Headers["X-Request-Id"] = requestId;
|
||||
|
||||
return Results.Json(
|
||||
new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code,
|
||||
message,
|
||||
request_id = requestId
|
||||
}
|
||||
},
|
||||
statusCode: statusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Isopoh.Cryptography.Argon2;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class Argon2PasswordHasher : IPasswordHasher
|
||||
{
|
||||
// Минимум по рекомендации OWASP для Argon2id: m=19 MiB, t=2, p=1. Обоснование и выбор — в REPORT.md.
|
||||
private const int TimeCost = 2;
|
||||
private const int MemoryCostKiB = 19 * 1024;
|
||||
private const int Parallelism = 1;
|
||||
|
||||
// Каждое вычисление занимает ~19 MiB и ядро CPU: без лимита 100 параллельных входов = ~2 GiB памяти.
|
||||
// Размер и время ожидания слотов задаются PASSWORD_HASH_CONCURRENCY / PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS.
|
||||
private readonly SemaphoreSlim _slots;
|
||||
private readonly TimeSpan _slotWaitTimeout;
|
||||
|
||||
// Хеш от случайного пароля, который никто не знает. Нужен только для выравнивания времени при неизвестном username.
|
||||
private readonly string _dummyHash;
|
||||
|
||||
public Argon2PasswordHasher(PasswordHashingSettings settings)
|
||||
{
|
||||
_slots = new SemaphoreSlim(settings.MaxConcurrency, settings.MaxConcurrency);
|
||||
_slotWaitTimeout = settings.QueueTimeout;
|
||||
_dummyHash = HashCore(Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)));
|
||||
}
|
||||
|
||||
public async Task<string> HashAsync(string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => HashCore(password), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyAsync(string? hash, string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var ok = Argon2.Verify(hash ?? _dummyHash, password, secret: null, secureArrayCall: null);
|
||||
return hash is not null && ok;
|
||||
}, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcquireSlotAsync(CancellationToken ct)
|
||||
{
|
||||
if (!await _slots.WaitAsync(_slotWaitTimeout, ct))
|
||||
{
|
||||
throw new PasswordHasherBusyException();
|
||||
}
|
||||
}
|
||||
|
||||
// HybridAddressing — это Argon2id. Соль генерируется библиотекой и входит в возвращаемую строку.
|
||||
private static string HashCore(string password) =>
|
||||
Argon2.Hash(password, TimeCost, MemoryCostKiB, Parallelism, Argon2Type.HybridAddressing);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class BearerAuth
|
||||
{
|
||||
public const string Scheme = "Bearer";
|
||||
public const string Challenge = "Bearer realm=\"messenger\"";
|
||||
public const string SessionIdClaim = "session_id";
|
||||
|
||||
// Ровно один заголовок Authorization вида "Bearer <token>"; иначе null (Basic и прочее здесь не принимаются).
|
||||
public static string? ExtractToken(HttpRequest request)
|
||||
{
|
||||
if (request.Headers.Authorization.Count != 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var value = request.Headers.Authorization[0];
|
||||
const string prefix = "Bearer ";
|
||||
if (value is null || !value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var token = value[prefix.Length..].Trim();
|
||||
return token.Length == 0 ? null : token;
|
||||
}
|
||||
|
||||
public static Guid GetUserId(this HttpContext context) =>
|
||||
Guid.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
|
||||
public static Guid GetSessionId(this HttpContext context) =>
|
||||
Guid.Parse(context.User.FindFirstValue(SessionIdClaim)!);
|
||||
}
|
||||
|
||||
// Стандартный обработчик аутентификации ASP.NET: превращает Bearer-токен в ClaimsPrincipal.
|
||||
// Срабатывает до выбора и выполнения эндпоинта (в том числе до разбора тела), поэтому 401 всегда раньше 400/404.
|
||||
public sealed class SessionAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
MessengerDbContext db)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var token = BearerAuth.ExtractToken(Request);
|
||||
if (token is null)
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
var hash = SessionTokens.Hash(token);
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
|
||||
// Неизвестный, истёкший и отозванный токен неразличимы для клиента: во всех случаях это один 401.
|
||||
var session = await db.Sessions
|
||||
.AsNoTracking()
|
||||
.Where(s => s.TokenHash == hash && s.RevokedAt == null && s.ExpiresAt > now)
|
||||
.Select(s => new { s.Id, s.UserId })
|
||||
.FirstOrDefaultAsync(Context.RequestAborted);
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
return AuthenticateResult.Fail("Недействительная сессия");
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, session.UserId.ToString()),
|
||||
new Claim(BearerAuth.SessionIdClaim, session.Id.ToString())
|
||||
],
|
||||
BearerAuth.Scheme);
|
||||
|
||||
return AuthenticateResult.Success(
|
||||
new AuthenticationTicket(new ClaimsPrincipal(identity), BearerAuth.Scheme));
|
||||
}
|
||||
|
||||
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
await ApiErrors
|
||||
.Unauthorized(Context, BearerAuth.Challenge, "Требуется действительный Bearer-токен")
|
||||
.ExecuteAsync(Context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
// Непрозрачный для клиента cursor keyset-пагинации: (created_at, id) последнего элемента страницы.
|
||||
// Привязан к ресурсу (scope): cursor от другого списка или чата отклоняется как 400.
|
||||
public static class Cursors
|
||||
{
|
||||
public const string Chats = "chats";
|
||||
|
||||
public static string Messages(Guid chatId) => $"messages/{chatId:D}";
|
||||
|
||||
public static string Encode(string scope, DateTimeOffset createdAt, Guid id) =>
|
||||
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{scope}|{createdAt.UtcTicks}:{id:D}"));
|
||||
|
||||
// cursor == null — первая страница (успех, value == null). Любая ошибка формата или чужой scope — false.
|
||||
public static bool TryDecode(string? cursor, string scope, out (DateTimeOffset CreatedAt, Guid Id)? value)
|
||||
{
|
||||
value = null;
|
||||
if (cursor is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cursor.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var decoded = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(Convert.FromBase64String(cursor));
|
||||
var scoped = decoded.Split('|', 2);
|
||||
if (scoped.Length != 2 || scoped[0] != scope)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = scoped[1].Split(':', 2);
|
||||
if (parts.Length != 2 ||
|
||||
!long.TryParse(parts[0], out var ticks) ||
|
||||
ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks ||
|
||||
!Guid.TryParse(parts[1], out var id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = (new DateTimeOffset(ticks, TimeSpan.Zero), id);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or ArgumentException or DecoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Data.Common;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class QueryCounter
|
||||
{
|
||||
public int Count;
|
||||
}
|
||||
|
||||
// Считает SQL-команды, выполненные EF Core в рамках текущего HTTP-запроса (для измерения «запросов к БД на запрос API»).
|
||||
// Включается только при DIAGNOSTIC_HEADERS=true. Команда ReserveMessageSlot (сырой NpgsqlCommand) не учитывается.
|
||||
public sealed class QueryCountingInterceptor(IHttpContextAccessor accessor) : DbCommandInterceptor
|
||||
{
|
||||
public const string ItemKey = "diagnostics.query_counter";
|
||||
|
||||
private void Count()
|
||||
{
|
||||
if (accessor.HttpContext?.Items[ItemKey] is QueryCounter counter)
|
||||
{
|
||||
Interlocked.Increment(ref counter.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DependencyFailures
|
||||
{
|
||||
// Недоступность или перегрузка PostgreSQL (нет соединения, таймаут, исчерпан пул, остановка сервера) — это 503,
|
||||
// а не 500: ошибка ограничена, внутренние детали не раскрываются, запрос не принимается как доверенный.
|
||||
public static bool IsDatabaseUnavailable(Exception? error)
|
||||
{
|
||||
for (var e = error; e is not null; e = e.InnerException)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case PostgresException pg:
|
||||
// 08 — соединение, 53 — нехватка ресурсов, 57 — вмешательство оператора (shutdown и т.п.)
|
||||
if (pg.SqlState.StartsWith("08") || pg.SqlState.StartsWith("53") || pg.SqlState.StartsWith("57"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
break;
|
||||
case NpgsqlException:
|
||||
case TimeoutException:
|
||||
case System.Net.Sockets.SocketException:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public interface IPasswordHasher
|
||||
{
|
||||
/// <summary>PHC-строка Argon2id (соль и параметры внутри). Бросает <see cref="PasswordHasherBusyException"/>, если слот не освободился вовремя.</summary>
|
||||
Task<string> HashAsync(string password, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="hash"/> == null означает «пользователя нет»: проверка всё равно выполняется (против заглушки),
|
||||
/// чтобы время ответа не раскрывало существование username.
|
||||
/// </summary>
|
||||
Task<bool> VerifyAsync(string? hash, string password, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PasswordHasherBusyException : Exception
|
||||
{
|
||||
public PasswordHasherBusyException() : base("Слишком много одновременных вычислений хеша пароля") { }
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public enum ClaimResult
|
||||
{
|
||||
Claimed, // ключ наш: можно выполнять побочный эффект (вставку сообщения) в этой же транзакции
|
||||
Replay, // такой ключ с тем же телом уже выполнен: вернуть сохранённое сообщение
|
||||
Conflict // такой ключ уже использован с другим телом
|
||||
}
|
||||
|
||||
public static partial class IdempotencyKeys
|
||||
{
|
||||
public const string HeaderName = "Idempotency-Key";
|
||||
|
||||
[GeneratedRegex("^[A-Za-z0-9._:-]{1,128}$")]
|
||||
private static partial Regex KeyFormat();
|
||||
|
||||
// Ровно один заголовок допустимого формата; иначе null (→ 400).
|
||||
public static string? ReadKey(HttpRequest request)
|
||||
{
|
||||
var values = request.Headers[HeaderName];
|
||||
return values.Count == 1 && values[0] is { } key && KeyFormat().IsMatch(key) ? key : null;
|
||||
}
|
||||
|
||||
// Отпечаток смысла запроса, а не его байтов: порядок ключей JSON и пробелы не влияют, потому что хешируются
|
||||
// уже разобранные поля. Для текстового сообщения это сам text (длина кодируется, чтобы поля не склеивались).
|
||||
public static byte[] RequestHash(string text) =>
|
||||
SHA256.HashData(Encoding.UTF8.GetBytes($"message\n{text.Length}\n{text}"));
|
||||
|
||||
// Атомарно «занимает» ключ в транзакции вызывающего. Ключевое свойство — INSERT ... ON CONFLICT:
|
||||
// * ключа нет → строка вставляется, мы владеем ключом (Claimed);
|
||||
// * ключ вставила другая, ещё не завершённая транзакция (в том числе на другой реплике) → INSERT ЖДЁТ её
|
||||
// COMMIT/ROLLBACK на уникальном индексе. После COMMIT вставки не происходит, и мы читаем её результат (Replay);
|
||||
// после ROLLBACK (например, 5xx у конкурента) вставка проходит, и ключ достаётся нам;
|
||||
// * ключ есть, но истёк → перезахватывается (DO UPDATE ... WHERE expires_at <= now).
|
||||
// Поэтому claim и сообщение коммитятся вместе: запись «ключ → сообщение» не может появиться без сообщения и наоборот.
|
||||
public static async Task<(ClaimResult Result, Guid MessageId)> ClaimAsync(
|
||||
MessengerDbContext db,
|
||||
IDbContextTransaction tx,
|
||||
Guid userId,
|
||||
Guid chatId,
|
||||
string key,
|
||||
byte[] requestHash,
|
||||
Guid newMessageId,
|
||||
TimeSpan ttl,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var connection = (NpgsqlConnection)db.Database.GetDbConnection();
|
||||
var transaction = (NpgsqlTransaction)tx.GetDbTransaction();
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
|
||||
await using (var insert = new NpgsqlCommand("""
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id, created_at, expires_at)
|
||||
VALUES (@user, @chat, @key, @hash, @message, @now, @expires)
|
||||
ON CONFLICT (user_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE idempotency_keys.expires_at <= EXCLUDED.created_at
|
||||
RETURNING 1
|
||||
""", connection, transaction))
|
||||
{
|
||||
insert.Parameters.AddWithValue("user", userId);
|
||||
insert.Parameters.AddWithValue("chat", chatId);
|
||||
insert.Parameters.AddWithValue("key", key);
|
||||
insert.Parameters.AddWithValue("hash", requestHash);
|
||||
insert.Parameters.AddWithValue("message", newMessageId);
|
||||
insert.Parameters.AddWithValue("now", now);
|
||||
insert.Parameters.AddWithValue("expires", now + ttl);
|
||||
|
||||
if (await insert.ExecuteScalarAsync(ct) is not null)
|
||||
{
|
||||
return (ClaimResult.Claimed, newMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
await using var select = new NpgsqlCommand("""
|
||||
SELECT request_hash, message_id FROM idempotency_keys
|
||||
WHERE user_id = @user AND chat_id = @chat AND key = @key
|
||||
""", connection, transaction);
|
||||
select.Parameters.AddWithValue("user", userId);
|
||||
select.Parameters.AddWithValue("chat", chatId);
|
||||
select.Parameters.AddWithValue("key", key);
|
||||
|
||||
await using var reader = await select.ExecuteReaderAsync(ct);
|
||||
if (!await reader.ReadAsync(ct))
|
||||
{
|
||||
// Строку успел удалить очиститель между INSERT и SELECT: крайне редко; клиент безопасно повторит запрос.
|
||||
throw new TimeoutException("idempotency key disappeared during claim");
|
||||
}
|
||||
|
||||
var storedHash = reader.GetFieldValue<byte[]>(0);
|
||||
var storedMessage = reader.GetGuid(1);
|
||||
return CryptographicOperations.FixedTimeEquals(storedHash, requestHash)
|
||||
? (ClaimResult.Replay, storedMessage)
|
||||
: (ClaimResult.Conflict, storedMessage);
|
||||
}
|
||||
}
|
||||
|
||||
// Периодически удаляет истёкшие ключи. Запускается на каждой реплике; параллельные DELETE безопасны
|
||||
// (физически строку удалит одна из них, остальные удалят 0).
|
||||
public sealed class IdempotencyCleaner(
|
||||
IServiceScopeFactory scopes,
|
||||
IdempotencySettings settings,
|
||||
ILogger<IdempotencyCleaner> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(settings.CleanupInterval);
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
var removed = await db.IdempotencyKeys.Where(k => k.ExpiresAt <= now).ExecuteDeleteAsync(stoppingToken);
|
||||
if (removed > 0)
|
||||
{
|
||||
logger.LogInformation("Удалено истёкших ключей идемпотентности: {Count}", removed);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning("Очистка ключей идемпотентности не удалась ({Error}); повтор через {Seconds} с",
|
||||
ex.GetType().Name, settings.CleanupInterval.TotalSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// остановка приложения
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public enum CacheStatus
|
||||
{
|
||||
Disabled, // кэш не настроен
|
||||
Hit,
|
||||
Miss,
|
||||
Bypass // кэш настроен, но недоступен: запрос обслужен напрямую из PostgreSQL
|
||||
}
|
||||
|
||||
// Кэш страниц истории. Источник истины — PostgreSQL; кэш лишь ускоряет чтение и никогда не обязателен.
|
||||
// Согласованность: версия истории чата (chats.history_version) входит в ключ, а версия читается из PostgreSQL
|
||||
// при каждом запросе (см. MessageEndpoints). Запись увеличивает версию в своей транзакции, поэтому
|
||||
// после подтверждённой записи ключ меняется, и устаревшая страница недостижима — явная инвалидация не нужна.
|
||||
// Старые ключи удаляются по TTL (CACHE_TTL_SECONDS) и вытесняются политикой maxmemory.
|
||||
public interface IMessageHistoryCache
|
||||
{
|
||||
Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct);
|
||||
Task SetAsync(string key, string json, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class NullMessageHistoryCache : IMessageHistoryCache
|
||||
{
|
||||
public Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct) =>
|
||||
Task.FromResult<(string?, CacheStatus)>((null, CacheStatus.Disabled));
|
||||
|
||||
public Task SetAsync(string key, string json, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
public sealed class ValkeyMessageHistoryCache : IMessageHistoryCache, IDisposable
|
||||
{
|
||||
// После ошибки кэш пропускается на это время, чтобы каждый запрос не ждал таймаут недоступного сервера.
|
||||
private static readonly TimeSpan BypassWindow = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly ConnectionMultiplexer _connection;
|
||||
private readonly TimeSpan _ttl;
|
||||
private readonly ILogger<ValkeyMessageHistoryCache> _logger;
|
||||
private long _bypassUntilTicks;
|
||||
|
||||
public ValkeyMessageHistoryCache(CacheSettings settings, ILogger<ValkeyMessageHistoryCache> logger)
|
||||
{
|
||||
var options = ConfigurationOptions.Parse(settings.Connection!);
|
||||
// Недоступный кэш не должен ронять ни старт, ни запросы: короткие таймауты, подключение в фоне.
|
||||
options.AbortOnConnectFail = false;
|
||||
options.ConnectTimeout = 500;
|
||||
options.SyncTimeout = 200;
|
||||
options.AsyncTimeout = 200;
|
||||
options.ConnectRetry = 1;
|
||||
_connection = ConnectionMultiplexer.Connect(options);
|
||||
_ttl = settings.Ttl;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct)
|
||||
{
|
||||
if (IsBypassed())
|
||||
{
|
||||
return (null, CacheStatus.Bypass);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var value = await _connection.GetDatabase().StringGetAsync(key);
|
||||
return value.IsNull ? (null, CacheStatus.Miss) : ((string?)value, CacheStatus.Hit);
|
||||
}
|
||||
catch (Exception ex) when (ex is RedisException or TimeoutException)
|
||||
{
|
||||
StartBypass(ex);
|
||||
return (null, CacheStatus.Bypass);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SetAsync(string key, string json, CancellationToken ct)
|
||||
{
|
||||
if (IsBypassed())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _connection.GetDatabase().StringSetAsync(key, json, _ttl);
|
||||
}
|
||||
catch (Exception ex) when (ex is RedisException or TimeoutException)
|
||||
{
|
||||
StartBypass(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsBypassed() => Environment.TickCount64 < Interlocked.Read(ref _bypassUntilTicks);
|
||||
|
||||
private void StartBypass(Exception ex)
|
||||
{
|
||||
Interlocked.Exchange(ref _bypassUntilTicks, Environment.TickCount64 + (long)BypassWindow.TotalMilliseconds);
|
||||
_logger.LogWarning("Кэш недоступен ({Error}); чтение идёт напрямую из PostgreSQL ближайшие {Seconds} с",
|
||||
ex.GetType().Name, BypassWindow.TotalSeconds);
|
||||
}
|
||||
|
||||
public void Dispose() => _connection.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class SessionTokens
|
||||
{
|
||||
// 32 случайных байта = 256 бит энтропии (контракт: не менее 256). В base64url это 43 символа.
|
||||
public static string Generate() =>
|
||||
Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
|
||||
// В БД хранится только SHA-256 токена. Быстрый хеш здесь уместен: токен случайный и длинный, подбирать нечего
|
||||
// (в отличие от пароля, который выбирает человек и который поэтому хешируется медленным Argon2id).
|
||||
public static byte[] Hash(string token) => SHA256.HashData(Encoding.UTF8.GetBytes(token));
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
// Все настройки читаются из IConfiguration (переменные окружения и, в тестах, UseSetting), а не напрямую из окружения:
|
||||
// так одно приложение можно поднять с разными настройками в одном процессе. Секреты передаются файлами (*_FILE).
|
||||
|
||||
public sealed record DatabaseSettings(string ConnectionString)
|
||||
{
|
||||
public static DatabaseSettings From(IConfiguration configuration)
|
||||
{
|
||||
var file = configuration["DATABASE_URL_FILE"]
|
||||
?? throw new InvalidOperationException("DATABASE_URL_FILE не задан");
|
||||
|
||||
var builder = new Npgsql.NpgsqlConnectionStringBuilder(File.ReadAllText(file).Trim())
|
||||
{
|
||||
Pooling = true,
|
||||
MinPoolSize = 1,
|
||||
// Ограниченный пул: больше MaxPoolSize соединений от одного экземпляра не открывается,
|
||||
// ожидающие запросы ждут не дольше Timeout и затем получают 503.
|
||||
MaxPoolSize = configuration.GetValue("DB_MAX_POOL_SIZE", 20),
|
||||
Timeout = configuration.GetValue("DB_CONNECT_TIMEOUT_SECONDS", 5),
|
||||
CommandTimeout = configuration.GetValue("DB_COMMAND_TIMEOUT_SECONDS", 5)
|
||||
};
|
||||
return new DatabaseSettings(builder.ConnectionString);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record AuthSessionOptions(TimeSpan Ttl)
|
||||
{
|
||||
// SESSION_TTL_SECONDS: по умолчанию 3600; в тесте истечения допустимо 2. Неверное значение — ошибка старта, а не молчаливый дефолт.
|
||||
public static AuthSessionOptions From(IConfiguration configuration)
|
||||
{
|
||||
var raw = configuration["SESSION_TTL_SECONDS"];
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
return new AuthSessionOptions(TimeSpan.FromSeconds(3600));
|
||||
}
|
||||
|
||||
if (!int.TryParse(raw, out var seconds) || seconds < 1)
|
||||
{
|
||||
throw new InvalidOperationException("SESSION_TTL_SECONDS должен быть положительным целым числом");
|
||||
}
|
||||
|
||||
return new AuthSessionOptions(TimeSpan.FromSeconds(seconds));
|
||||
}
|
||||
}
|
||||
|
||||
// Ограничитель Argon2: сколько хешей считается одновременно и сколько запрос ждёт свободный слот, прежде чем получить 503.
|
||||
// Один хеш занимает ~19 MiB и ядро CPU, поэтому без лимита пачка регистраций исчерпала бы память.
|
||||
public sealed record PasswordHashingSettings(int MaxConcurrency, TimeSpan QueueTimeout)
|
||||
{
|
||||
public static PasswordHashingSettings From(IConfiguration configuration)
|
||||
{
|
||||
var concurrency = configuration.GetValue("PASSWORD_HASH_CONCURRENCY", 4);
|
||||
var timeoutSeconds = configuration.GetValue("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", 2.0);
|
||||
if (concurrency < 1 || timeoutSeconds < 0)
|
||||
{
|
||||
throw new InvalidOperationException("PASSWORD_HASH_CONCURRENCY >= 1 и PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS >= 0");
|
||||
}
|
||||
|
||||
return new PasswordHashingSettings(concurrency, TimeSpan.FromSeconds(timeoutSeconds));
|
||||
}
|
||||
}
|
||||
|
||||
// Кэш необязателен: без CACHE_URL_FILE / CACHE_CONNECTION приложение работает только на PostgreSQL.
|
||||
public sealed record CacheSettings(string? Connection, TimeSpan Ttl)
|
||||
{
|
||||
public bool Enabled => !string.IsNullOrWhiteSpace(Connection);
|
||||
|
||||
public static CacheSettings From(IConfiguration configuration)
|
||||
{
|
||||
var connection = configuration["CACHE_CONNECTION"];
|
||||
var file = configuration["CACHE_URL_FILE"];
|
||||
if (!string.IsNullOrWhiteSpace(file) && File.Exists(file))
|
||||
{
|
||||
connection = File.ReadAllText(file).Trim();
|
||||
}
|
||||
|
||||
return new CacheSettings(connection, TimeSpan.FromSeconds(configuration.GetValue("CACHE_TTL_SECONDS", 300)));
|
||||
}
|
||||
}
|
||||
|
||||
// Диагностические заголовки X-Cache и X-Db-Queries для экспериментов; в обычной работе выключены.
|
||||
public sealed record DiagnosticsSettings(bool Headers)
|
||||
{
|
||||
public static DiagnosticsSettings From(IConfiguration configuration) =>
|
||||
new(configuration.GetValue("DIAGNOSTIC_HEADERS", false));
|
||||
}
|
||||
|
||||
// Идентичность и жизненный цикл экземпляра (lab3).
|
||||
// InstanceId — значение X-Instance-Id. В Docker hostname контейнера = первые 12 символов его ID, поэтому
|
||||
// stop-one.sh по заголовку находит нужный контейнер. DrainDelay — пауза между SIGTERM и закрытием слушателя:
|
||||
// за это время /health/ready уже отвечает 503, и балансировщик успевает вывести экземпляр из ротации.
|
||||
// MigrateOnStart по умолчанию выключен: миграции выполняет отдельный one-shot контейнер (--migrate), а не гонка реплик.
|
||||
public sealed record InstanceSettings(string InstanceId, TimeSpan DrainDelay, bool MigrateOnStart)
|
||||
{
|
||||
public static InstanceSettings From(IConfiguration configuration)
|
||||
{
|
||||
var id = configuration["INSTANCE_ID"];
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
id = Environment.MachineName;
|
||||
}
|
||||
|
||||
var drainSeconds = configuration.GetValue("SHUTDOWN_DRAIN_SECONDS", 3.0);
|
||||
if (drainSeconds < 0)
|
||||
{
|
||||
throw new InvalidOperationException("SHUTDOWN_DRAIN_SECONDS должен быть >= 0");
|
||||
}
|
||||
|
||||
return new InstanceSettings(id, TimeSpan.FromSeconds(drainSeconds), configuration.GetValue("MIGRATE_ON_START", false));
|
||||
}
|
||||
}
|
||||
|
||||
// Время хранения результата идемпотентной отправки сообщения (контракт: не менее 24 часов).
|
||||
public sealed record IdempotencySettings(TimeSpan Ttl, TimeSpan CleanupInterval)
|
||||
{
|
||||
public static IdempotencySettings From(IConfiguration configuration)
|
||||
{
|
||||
var ttl = configuration.GetValue("IDEMPOTENCY_TTL_SECONDS", 86400);
|
||||
var cleanup = configuration.GetValue("IDEMPOTENCY_CLEANUP_INTERVAL_SECONDS", 300);
|
||||
if (ttl < 1 || cleanup < 1)
|
||||
{
|
||||
throw new InvalidOperationException("IDEMPOTENCY_TTL_SECONDS и IDEMPOTENCY_CLEANUP_INTERVAL_SECONDS должны быть положительными");
|
||||
}
|
||||
|
||||
return new IdempotencySettings(TimeSpan.FromSeconds(ttl), TimeSpan.FromSeconds(cleanup));
|
||||
}
|
||||
}
|
||||
|
||||
// Признак «экземпляр останавливается»: после SIGTERM /health/ready отвечает 503, а уже принятые запросы дорабатывают.
|
||||
public sealed class ShutdownState
|
||||
{
|
||||
private volatile bool _draining;
|
||||
public bool Draining => _draining;
|
||||
public void StartDraining() => _draining = true;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class Timestamps
|
||||
{
|
||||
// Единая точность времени для хранения, сортировки, cursor и JSON-ответа: миллисекунды.
|
||||
// Клиент видит время с точностью до миллисекунды, поэтому порядок (created_at, id) должен
|
||||
// определяться теми же значениями, которые он видит.
|
||||
public static DateTimeOffset UtcNowMilliseconds()
|
||||
{
|
||||
var ticks = DateTimeOffset.UtcNow.UtcTicks;
|
||||
return new DateTimeOffset(ticks - ticks % TimeSpan.TicksPerMillisecond, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class UtcDateTimeOffsetJsonConverter : JsonConverter<DateTimeOffset>
|
||||
{
|
||||
public override DateTimeOffset Read(
|
||||
ref Utf8JsonReader reader,
|
||||
Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
return DateTimeOffset.Parse(
|
||||
reader.GetString()!,
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind);
|
||||
}
|
||||
|
||||
public override void Write(
|
||||
Utf8JsonWriter writer,
|
||||
DateTimeOffset value,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStringValue(
|
||||
value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user