Реализация 5 лабораторной работы

This commit is contained in:
2026-11-27 20:06:14 +03:00
parent 276dbdad8a
commit 4fe4ab3432
116 changed files with 11883 additions and 25 deletions
+135
View File
@@ -0,0 +1,135 @@
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;
using Amazon.S3;
using Amazon.S3.Model;
using Messenger.Api.Jobs;
using Microsoft.Extensions.DependencyInjection;
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;
private string _s3AccessFile = string.Empty;
private string _s3SecretFile = string.Empty;
private const string S3Access = "integration-test-user";
private const string S3Secret = "integration-only-not-a-real-secret";
private readonly IContainer _s3 = new ContainerBuilder()
.WithImage("quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e")
.WithEnvironment("MINIO_ROOT_USER", S3Access)
.WithEnvironment("MINIO_ROOT_PASSWORD", S3Secret)
.WithEnvironment("MINIO_BROWSER", "off")
.WithCommand("server", "/data")
.WithPortBinding(9000, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(9000).ForPath("/minio/health/ready")))
.Build();
public string ConnectionString => _db.GetConnectionString();
public string CacheConnection => $"{_cache.Hostname}:{_cache.GetMappedPublicPort(6379)}";
public async Task InitializeAsync()
{
await Task.WhenAll(_db.StartAsync(), _cache.StartAsync(), _s3.StartAsync());
_connectionFile = WriteConnectionFile(_db.GetConnectionString());
_s3AccessFile = WriteConnectionFile(S3Access);
_s3SecretFile = WriteConnectionFile(S3Secret);
using var client = new AmazonS3Client(S3Access, S3Secret, new AmazonS3Config
{ ServiceURL = $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}", ForcePathStyle = true, AuthenticationRegion = "us-east-1" });
await client.PutBucketAsync(new PutBucketRequest { BucketName = "integration-attachments" });
}
async Task IAsyncLifetime.DisposeAsync()
{
await _db.DisposeAsync();
await _cache.DisposeAsync();
await _s3.DisposeAsync();
File.Delete(_connectionFile);
File.Delete(_s3AccessFile);
File.Delete(_s3SecretFile);
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseSetting("DATABASE_URL_FILE", _connectionFile);
builder.UseSetting("CACHE_CONNECTION", CacheConnection);
builder.UseSetting("DIAGNOSTIC_HEADERS", "true");
builder.UseSetting("S3_ENDPOINT", $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}");
builder.UseSetting("S3_BUCKET", "integration-attachments");
builder.UseSetting("S3_ACCESS_KEY_ID_FILE", _s3AccessFile);
builder.UseSetting("S3_SECRET_ACCESS_KEY_FILE", _s3SecretFile);
// В Compose схему применяет отдельный контейнер (--migrate); тестовый процесс мигрирует пустую БД сам.
builder.UseSetting("MIGRATE_ON_START", "true");
builder.UseSetting("SHUTDOWN_DRAIN_SECONDS", "0");
builder.ConfigureServices(services =>
{
services.AddSingleton(new JobSettings(2, TimeSpan.FromSeconds(30), 1, TimeSpan.FromHours(1)));
services.AddScoped<AttachmentProcessor>();
});
}
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>;
+104
View File
@@ -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;
}
}
+303
View File
@@ -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));
}
}
+252
View File
@@ -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);
}
}
+150
View File
@@ -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}();");
}
}
}
+28
View File
@@ -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"));
}
}
+261
View File
@@ -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));
}
}
+74
View File
@@ -0,0 +1,74 @@
using ImageMagick;
using Messenger.Api.Jobs;
namespace Messenger.Api.Tests;
public class ThumbnailTests
{
[Theory]
[InlineData(321, 200, 256, 159)]
[InlineData(1, 800, 1, 256)]
[InlineData(7, 9, 7, 9)]
public void FitsWithoutUpscalingAndCompositesAlphaOntoWhite(int w, int h, int expectedW, int expectedH)
{
using var source = new MagickImage(MagickColors.Transparent, (uint)w, (uint)h);
using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png));
var thumbnail = ImageVariant.CreateAll(input, "image/png", 40000000, 1)[0];
using var jpeg = new MagickImage(thumbnail.Bytes);
Assert.Equal(MagickFormat.Jpeg, jpeg.Format);
Assert.Equal((expectedW, expectedH), ((int)jpeg.Width, (int)jpeg.Height));
using var pixels = jpeg.GetPixels();
var color = pixels.GetPixel(0, 0).ToColor()!;
Assert.True(color.R >= 250 && color.G >= 250 && color.B >= 250);
}
[Fact]
public void AppliesExifOrientationBeforeSizing()
{
using var source = new MagickImage(MagickColors.Red, 320, 200);
var profile = new ExifProfile();
profile.SetValue(ExifTag.Orientation, (ushort)6);
source.SetProfile(profile);
source.Orientation = Orientation.RightTop;
using var input = new MemoryStream(source.ToByteArray(MagickFormat.Jpeg));
var variants = ImageVariant.CreateAll(input, "image/jpeg", 40000000, 1);
var thumb = Assert.Single(variants, v => v.Name == "thumbnail");
Assert.Equal((160, 256), (thumb.Width, thumb.Height));
foreach (var variant in variants)
{
using var decoded = new MagickImage(variant.Bytes);
Assert.Null(decoded.GetExifProfile());
}
}
[Fact]
public void UsesCentralCropAndFitsLargeWebPWithin1280Pixels()
{
using var source = new MagickImage(MagickColors.Red, 1600, 800);
using var center = new MagickImage(MagickColors.Lime, 1000, 800);
source.Composite(center, Gravity.Center, CompositeOperator.Over);
using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png));
var variants = ImageVariant.CreateAll(input, "image/png", 40000000, 1);
using var crop = new MagickImage(Assert.Single(variants, v => v.Name == "crop").Bytes);
Assert.Equal((128u, 128u), (crop.Width, crop.Height));
using var pixels = crop.GetPixels();
foreach (var x in new[] { 0, 127 })
{
var color = pixels.GetPixel(x, 64).ToColor()!;
Assert.True(color.G >= 240 && color.R <= 15);
}
using var optimized = new MagickImage(Assert.Single(variants, v => v.Name == "optimized").Bytes);
Assert.Equal(MagickFormat.WebP, optimized.Format);
Assert.Equal((1280u, 640u), (optimized.Width, optimized.Height));
}
[Fact]
public void RefusesAnImageOverThePixelLimit()
{
using var source = new MagickImage(MagickColors.Red, 11, 10);
using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png));
Assert.Throws<InvalidDataException>(() => ImageVariant.CreateAll(input, "image/png", 100, 1));
}
}
@@ -0,0 +1,220 @@
using System.Net;
using Amazon.S3;
using Messenger.Api.Data;
using Messenger.Api.Jobs;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using static Messenger.Api.Tests.ApiHelpers;
namespace Messenger.Api.Tests;
[Collection("api")]
public class UploadCleanupTests(ApiFixture fixture)
{
private static byte[] Png => File.ReadAllBytes(Path.Combine(FindRoot(), "tests/fixtures/sample.png"));
private static string FindRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "lab.json"))) dir = dir.Parent;
return dir?.FullName ?? throw new InvalidOperationException("Repository root missing");
}
private static async Task<HttpResponseMessage> Upload(HttpClient client, TestUser user, Guid chat, string filename)
{
using var content = new ByteArrayContent(Png);
content.Headers.ContentType = new("image/png");
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/attachments?filename={filename}", user, content);
return await client.SendAsync(request);
}
private sealed class MetadataFailure : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData data,
InterceptionResult<int> result, CancellationToken ct = default)
{
if (data.Context!.ChangeTracker.Entries<AttachmentEntity>().Any(e => e.State == EntityState.Added))
throw new InvalidOperationException("injected metadata commit failure");
return ValueTask.FromResult(result);
}
}
private sealed class StorageDecorator(IAttachmentStorage inner) : IAttachmentStorage, IDisposable
{
public bool FailDelete { get; set; }
public Func<string, Task>? AfterPut { get; set; }
public Task CheckAsync(CancellationToken ct) => inner.CheckAsync(ct);
public async Task PutAsync(string key, Stream content, string mime, CancellationToken ct, bool createOnly = false)
{ await inner.PutAsync(key, content, mime, ct, createOnly); if (AfterPut is not null) await AfterPut(key); }
public Task CopyToAsync(string key, Stream output, CancellationToken ct) => inner.CopyToAsync(key, output, ct);
public Task DeleteAsync(string key, CancellationToken ct) => FailDelete
? throw new HttpRequestException("injected S3 outage") : inner.DeleteAsync(key, ct);
public void Dispose() => (inner as IDisposable)?.Dispose();
}
private async Task<UploadIntentEntity> Seed(IServiceProvider services, bool expired = true)
{
using var scope = services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
var id = Guid.NewGuid();
var now = Timestamps.UtcNowMilliseconds();
var intent = new UploadIntentEntity { Id = id, ObjectKey = $"staging/{id:N}", CreatedAt = now,
ExpiresAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5), NextAttemptAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5) };
db.UploadIntents.Add(intent);
await db.SaveChangesAsync();
await scope.ServiceProvider.GetRequiredService<IAttachmentStorage>().PutAsync(intent.ObjectKey,
new MemoryStream(Png), "image/png", CancellationToken.None);
return intent;
}
private static async Task AssertMissing(IServiceProvider services, string key)
{
var storage = services.GetRequiredService<IAttachmentStorage>();
var error = await Assert.ThrowsAnyAsync<AmazonS3Exception>(() => storage.CopyToAsync(key, Stream.Null, CancellationToken.None));
Assert.Equal(HttpStatusCode.NotFound, error.StatusCode);
}
[Fact]
public async Task MetadataFailureAfterS3Put_SurvivesApiRecreation_AndIsCleaned()
{
Guid pendingId;
string key;
var filename = $"fault-{Guid.NewGuid():N}.png";
await using (var broken = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
services.AddDbContext<MessengerDbContext>(options => options.AddInterceptors(new MetadataFailure())))))
{
using var client = broken.CreateClient();
var user = await CreateUserAsync(client);
var chat = await CreateChatAsync(client, user);
var response = await Upload(client, user, chat, filename);
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
using var scope = broken.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
Assert.False(await db.Attachments.AnyAsync(a => a.Filename == filename));
var intent = await db.UploadIntents.OrderByDescending(i => i.CreatedAt).FirstAsync();
pendingId = intent.Id; key = intent.ObjectKey;
using var output = new MemoryStream();
await broken.Services.GetRequiredService<IAttachmentStorage>().CopyToAsync(key, output, CancellationToken.None);
Assert.Equal(Png, output.ToArray());
}
// Новый экземпляр приложения читает тот же устойчивый журнал.
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{pendingId}'");
await using var recovered = fixture.WithWebHostBuilder(_ => { });
using var recoveredClient = recovered.CreateClient();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",pendingId)) == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
await AssertMissing(recovered.Services, key);
Assert.Equal(1L, await fixture.ScalarAsync<long>("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0", ("id",pendingId)));
}
[Fact]
public async Task FreshIntent_IsProtectedByGracePeriod()
{
using var client = fixture.CreateClient();
var intent = await Seed(fixture.Services, expired: false);
await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
using var result = new MemoryStream();
await fixture.Services.GetRequiredService<IAttachmentStorage>().CopyToAsync(intent.ObjectKey, result, CancellationToken.None);
Assert.Equal(Png, result.ToArray());
Assert.Equal(0, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
}
[Fact]
public async Task PublishedAttachment_IsNeverDeleted_EvenWithAnExpiredIntent()
{
using var client = fixture.CreateClient();
var user = await CreateUserAsync(client);
var chat = await CreateChatAsync(client, user);
var response = await Upload(client, user, chat, "protected.png");
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
using (var worker = fixture.Services.CreateScope())
{
var job = await worker.ServiceProvider.GetRequiredService<MessengerDbContext>().AttachmentJobs.SingleAsync(j => j.AttachmentId == id);
await worker.ServiceProvider.GetRequiredService<AttachmentProcessor>().ProcessAsync(JobMessage.From(job), CancellationToken.None);
}
using var scope = fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
var attachment = await db.Attachments.SingleAsync(a => a.Id == id);
Assert.Equal("ready", attachment.Status);
var old = DateTimeOffset.UtcNow.AddMinutes(-1);
// У оригинала отдельная проверочная запись. После ready worker планирует уборку staging с ID вложения.
var staleIntentId = Guid.NewGuid();
db.UploadIntents.Add(new() { Id = staleIntentId, ObjectKey = attachment.ObjectKey, CreatedAt = old,
ExpiresAt = old, NextAttemptAt = old });
await db.SaveChangesAsync();
await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
using var request = Request(HttpMethod.Get,$"/api/v1/attachments/{id}/content",user);
Assert.Equal(Png, await (await client.SendAsync(request)).Content.ReadAsByteArrayAsync());
Assert.False(await db.UploadIntents.AsNoTracking().AnyAsync(i => i.Id == staleIntentId));
}
[Fact]
public async Task CleanupRetriesAfterS3Failure_AndDeletesALatePutAgain()
{
StorageDecorator? decorator = null;
await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
services.AddSingleton<IAttachmentStorage>(sp => decorator = new(new S3AttachmentStorage(sp.GetRequiredService<S3Settings>())))));
using var client = app.CreateClient();
var intent = await Seed(app.Services);
decorator!.FailDelete = true;
var failed = await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
Assert.True(failed.Failed >= 1);
Assert.Equal(0, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
decorator.FailDelete = false;
await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'");
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
await AssertMissing(app.Services,intent.ObjectKey);
// Имитация PUT, завершившегося с задержкой после первого DELETE.
await decorator.PutAsync(intent.ObjectKey,new MemoryStream(Png),"image/png",CancellationToken.None);
await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'");
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
await AssertMissing(app.Services,intent.ObjectKey);
Assert.Equal(2, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
}
[Fact]
public async Task ExpiredUploadCannotPublish_AfterItsLeaseWasRevoked()
{
await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
services.AddSingleton<IAttachmentStorage>(sp => new StorageDecorator(new S3AttachmentStorage(sp.GetRequiredService<S3Settings>()))
{ AfterPut = async key =>
{
var id = Guid.ParseExact(key["staging/".Length..],"N");
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{id}'");
}
})));
using var client = app.CreateClient();
var user = await CreateUserAsync(client);
var chat = await CreateChatAsync(client,user);
var name = $"expired-{Guid.NewGuid():N}.png";
Assert.Equal(HttpStatusCode.ServiceUnavailable,(await Upload(client,user,chat,name)).StatusCode);
using var scope = app.Services.CreateScope();
Assert.False(await scope.ServiceProvider.GetRequiredService<MessengerDbContext>().Attachments.AnyAsync(a=>a.Filename==name));
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
}
[Fact]
public async Task ConcurrentCleaners_ClaimAnIntentOnce()
{
using var client = fixture.CreateClient();
var intent = await Seed(fixture.Services);
var cleaner = fixture.Services.GetRequiredService<UploadCleanup>();
await Task.WhenAll(cleaner.RunOnceAsync(CancellationToken.None),cleaner.RunOnceAsync(CancellationToken.None));
await AssertMissing(fixture.Services,intent.ObjectKey);
Assert.Equal(1,await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
}
[Fact]
public async Task OldTombstone_RemainsSoALatePutCannotBeForgotten()
{
using var client = fixture.CreateClient();
var intent = await Seed(fixture.Services);
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '2 days' WHERE id='{intent.Id}'");
await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
await AssertMissing(fixture.Services,intent.ObjectKey);
Assert.Equal(1L,await fixture.ScalarAsync<long>("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0",("id",intent.Id)));
}
}
@@ -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);
}
}
+130
View File
@@ -0,0 +1,130 @@
namespace Messenger.Api.Data;
// Долговечное намерение записать S3 object. Создаётся ДО PUT, удаляется атомарно
// с публикацией Attachment. После аварии остаётся для фоновой очистки.
public sealed class UploadIntentEntity
{
public Guid Id { get; set; }
public string ObjectKey { get; set; } = string.Empty;
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
public DateTimeOffset NextAttemptAt { get; set; }
public int DeleteCount { get; set; }
}
// Строки таблиц. 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 Guid[] AttachmentIds { 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; }
}
public sealed class AttachmentEntity
{
public Guid Id { get; set; }
public Guid ChatId { get; set; }
public Guid OwnerId { get; set; }
public string Filename { get; set; } = string.Empty;
public string ObjectKey { get; set; } = string.Empty;
public string ContentType { get; set; } = string.Empty;
public long SizeBytes { get; set; }
public string ChecksumSha256 { get; set; } = string.Empty;
public string Status { get; set; } = "queued";
public string? ErrorCode { get; set; }
public int PipelineVersion { get; set; } = 1;
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public List<AttachmentVariantEntity> Variants { get; set; } = [];
}
// The same row is the processing record and the transactional outbox until publication is confirmed.
public sealed class AttachmentJobEntity
{
public Guid Id { get; set; }
public Guid AttachmentId { get; set; }
public AttachmentEntity Attachment { get; set; } = null!;
public string SourceKey { get; set; } = string.Empty;
public int PipelineVersion { get; set; } = 1;
public int Attempt { get; set; } = 1;
public int FirstAttempt { get; set; } = 1;
public DateTimeOffset? ReplayedAt { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset NextAttemptAt { get; set; }
public DateTimeOffset? PublishedAt { get; set; }
public DateTimeOffset? LeaseUntil { get; set; }
}
public sealed class AttachmentVariantEntity
{
public Guid AttachmentId { get; set; }
public int PipelineVersion { get; set; }
public string Name { get; set; } = string.Empty;
public string ObjectKey { get; set; } = string.Empty;
public string ContentType { get; set; } = string.Empty;
public int Width { get; set; }
public int Height { get; set; }
public long SizeBytes { get; set; }
public string Sha256 { get; set; } = string.Empty;
}
@@ -0,0 +1,181 @@
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>();
public DbSet<AttachmentEntity> Attachments => Set<AttachmentEntity>();
public DbSet<UploadIntentEntity> UploadIntents => Set<UploadIntentEntity>();
public DbSet<AttachmentJobEntity> AttachmentJobs => Set<AttachmentJobEntity>();
public DbSet<AttachmentVariantEntity> AttachmentVariants => Set<AttachmentVariantEntity>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UploadIntentEntity>(e =>
{
e.ToTable("upload_intents");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedNever();
e.Property(x => x.ObjectKey).IsRequired();
e.HasIndex(x => x.ObjectKey).IsUnique();
e.HasIndex(x => new { x.NextAttemptAt, x.ExpiresAt });
});
// Идентификаторы создаёт приложение (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_or_attachments", @"text ~ '\S' OR cardinality(attachment_ids) > 0");
t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10");
});
// До 10 ссылок: храним порядок без дополнительных запросов для каждой строки истории.
e.Property(x => x.AttachmentIds).HasColumnType("uuid[]").HasDefaultValueSql("'{}'::uuid[]").IsRequired();
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");
});
modelBuilder.Entity<AttachmentJobEntity>(e =>
{
e.ToTable("attachment_jobs");
e.HasKey(j => j.Id);
e.Property(j => j.Id).ValueGeneratedNever();
e.Property(j => j.FirstAttempt).HasDefaultValue(1);
e.HasOne(j => j.Attachment).WithMany().HasForeignKey(j => j.AttachmentId);
e.HasIndex(j => new { j.AttachmentId, j.PipelineVersion }).IsUnique();
e.HasIndex(j => j.NextAttemptAt).HasFilter("published_at IS NULL");
e.HasIndex(j => j.LeaseUntil).HasFilter("lease_until IS NOT NULL");
});
modelBuilder.Entity<AttachmentVariantEntity>(e =>
{
e.ToTable("attachment_variants");
e.HasKey(v => new { v.AttachmentId, v.PipelineVersion, v.Name });
e.HasOne<AttachmentEntity>().WithMany(a => a.Variants).HasForeignKey(v => v.AttachmentId);
e.HasIndex(v => v.ObjectKey).IsUnique();
});
modelBuilder.Entity<AttachmentEntity>(e =>
{
e.ToTable("attachments");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedNever();
e.Property(x => x.Filename).HasMaxLength(255).IsRequired();
e.Property(x => x.ObjectKey).IsRequired();
e.Property(x => x.ContentType).HasMaxLength(100).IsRequired();
e.Property(x => x.ChecksumSha256).HasMaxLength(64).IsRequired();
e.Property(x => x.Status).HasMaxLength(20).IsRequired();
e.Property(x => x.PipelineVersion).HasDefaultValue(1);
e.HasIndex(x => x.ObjectKey).IsUnique();
e.HasIndex(x => x.ChatId);
e.HasOne<ChatEntity>()
.WithMany()
.HasForeignKey(x => x.ChatId)
.OnDelete(DeleteBehavior.Restrict);
e.HasOne<UserEntity>()
.WithMany()
.HasForeignKey(x => x.OwnerId)
.OnDelete(DeleteBehavior.Restrict);
});
}
}
@@ -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");
}
}
}
@@ -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");
}
}
}
@@ -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,389 @@
// <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("20261113163634_AddAttachments")]
partial class AddAttachments
{
/// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UploadedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("uploaded_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
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,71 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Messenger.Api.Data.Migrations
{
/// <inheritdoc />
public partial class AddAttachments : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "attachments",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
chat_id = table.Column<Guid>(type: "uuid", nullable: false),
owner_id = table.Column<Guid>(type: "uuid", nullable: false),
filename = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
object_key = table.Column<string>(type: "text", nullable: false),
content_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
size_bytes = table.Column<long>(type: "bigint", nullable: false),
checksum_sha256 = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
status = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
uploaded_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_attachments", x => x.id);
table.ForeignKey(
name: "fk_attachments_chats_chat_id",
column: x => x.chat_id,
principalTable: "chats",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_attachments_users_owner_id",
column: x => x.owner_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "ix_attachments_chat_id",
table: "attachments",
column: "chat_id");
migrationBuilder.CreateIndex(
name: "ix_attachments_object_key",
table: "attachments",
column: "object_key",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_attachments_owner_id",
table: "attachments",
column: "owner_id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "attachments");
}
}
}
@@ -0,0 +1,398 @@
// <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("20261113171218_AddMessageAttachments")]
partial class AddMessageAttachments
{
/// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UploadedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("uploaded_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
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.PrimitiveCollection<Guid[]>("AttachmentIds")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("uuid[]")
.HasColumnName("attachment_ids")
.HasDefaultValueSql("'{}'::uuid[]");
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_attachment_limit", "cardinality(attachment_ids) <= 10");
t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0");
});
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
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 AddMessageAttachments : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropCheckConstraint(
name: "ck_messages_text_not_blank",
table: "messages");
migrationBuilder.AddColumn<Guid[]>(
name: "attachment_ids",
table: "messages",
type: "uuid[]",
nullable: false,
defaultValueSql: "'{}'::uuid[]");
migrationBuilder.AddCheckConstraint(
name: "ck_messages_attachment_limit",
table: "messages",
sql: "cardinality(attachment_ids) <= 10");
migrationBuilder.AddCheckConstraint(
name: "ck_messages_text_or_attachments",
table: "messages",
sql: "text ~ '\\S' OR cardinality(attachment_ids) > 0");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropCheckConstraint(
name: "ck_messages_attachment_limit",
table: "messages");
migrationBuilder.DropCheckConstraint(
name: "ck_messages_text_or_attachments",
table: "messages");
migrationBuilder.DropColumn(
name: "attachment_ids",
table: "messages");
migrationBuilder.AddCheckConstraint(
name: "ck_messages_text_not_blank",
table: "messages",
sql: "text ~ '\\S'");
}
}
}
@@ -0,0 +1,438 @@
// <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("20261113175727_AddUploadIntents")]
partial class AddUploadIntents
{
/// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UploadedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("uploaded_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
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.PrimitiveCollection<Guid[]>("AttachmentIds")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("uuid[]")
.HasColumnName("attachment_ids")
.HasDefaultValueSql("'{}'::uuid[]");
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_attachment_limit", "cardinality(attachment_ids) <= 10");
t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0");
});
});
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.UploadIntentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("DeleteCount")
.HasColumnType("integer")
.HasColumnName("delete_count");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.HasKey("Id")
.HasName("pk_upload_intents");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_upload_intents_object_key");
b.HasIndex("NextAttemptAt", "ExpiresAt")
.HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at");
b.ToTable("upload_intents", (string)null);
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
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,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Messenger.Api.Data.Migrations
{
/// <inheritdoc />
public partial class AddUploadIntents : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "upload_intents",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
object_key = table.Column<string>(type: "text", 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),
next_attempt_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
delete_count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("pk_upload_intents", x => x.id);
});
migrationBuilder.CreateIndex(
name: "ix_upload_intents_next_attempt_at_expires_at",
table: "upload_intents",
columns: new[] { "next_attempt_at", "expires_at" });
migrationBuilder.CreateIndex(
name: "ix_upload_intents_object_key",
table: "upload_intents",
column: "object_key",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "upload_intents");
}
}
}
@@ -0,0 +1,577 @@
// <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("20261127162010_AsyncAttachments")]
partial class AsyncAttachments
{
/// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("ErrorCode")
.HasColumnType("text")
.HasColumnName("error_code");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("Attempt")
.HasColumnType("integer")
.HasColumnName("attempt");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<DateTimeOffset?>("LeaseUntil")
.HasColumnType("timestamp with time zone")
.HasColumnName("lease_until");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<DateTimeOffset?>("PublishedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("published_at");
b.Property<string>("SourceKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("source_key");
b.HasKey("Id")
.HasName("pk_attachment_jobs");
b.HasIndex("AttachmentId")
.IsUnique()
.HasDatabaseName("ix_attachment_jobs_attachment_id");
b.HasIndex("LeaseUntil")
.HasDatabaseName("ix_attachment_jobs_lease_until")
.HasFilter("lease_until IS NOT NULL");
b.HasIndex("NextAttemptAt")
.HasDatabaseName("ix_attachment_jobs_next_attempt_at")
.HasFilter("published_at IS NULL");
b.ToTable("attachment_jobs", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<string>("Name")
.HasColumnType("text")
.HasColumnName("name");
b.Property<string>("ContentType")
.IsRequired()
.HasColumnType("text")
.HasColumnName("content_type");
b.Property<int>("Height")
.HasColumnType("integer")
.HasColumnName("height");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<string>("Sha256")
.IsRequired()
.HasColumnType("text")
.HasColumnName("sha256");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<int>("Width")
.HasColumnType("integer")
.HasColumnName("width");
b.HasKey("AttachmentId", "PipelineVersion", "Name")
.HasName("pk_attachment_variants");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachment_variants_object_key");
b.ToTable("attachment_variants", (string)null);
});
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.PrimitiveCollection<Guid[]>("AttachmentIds")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("uuid[]")
.HasColumnName("attachment_ids")
.HasDefaultValueSql("'{}'::uuid[]");
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_attachment_limit", "cardinality(attachment_ids) <= 10");
t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0");
});
});
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.UploadIntentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("DeleteCount")
.HasColumnType("integer")
.HasColumnName("delete_count");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.HasKey("Id")
.HasName("pk_upload_intents");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_upload_intents_object_key");
b.HasIndex("NextAttemptAt", "ExpiresAt")
.HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at");
b.ToTable("upload_intents", (string)null);
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment")
.WithOne()
.HasForeignKey("Messenger.Api.Data.AttachmentJobEntity", "AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_jobs_attachments_attachment_id");
b.Navigation("Attachment");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", null)
.WithMany("Variants")
.HasForeignKey("AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_variants_attachments_attachment_id");
});
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");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b =>
{
b.Navigation("Variants");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,133 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Messenger.Api.Data.Migrations
{
/// <inheritdoc />
public partial class AsyncAttachments : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "uploaded_at",
table: "attachments",
newName: "updated_at");
migrationBuilder.AddColumn<string>(
name: "error_code",
table: "attachments",
type: "text",
nullable: true);
migrationBuilder.CreateTable(
name: "attachment_jobs",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
attachment_id = table.Column<Guid>(type: "uuid", nullable: false),
source_key = table.Column<string>(type: "text", nullable: false),
pipeline_version = table.Column<int>(type: "integer", nullable: false),
attempt = table.Column<int>(type: "integer", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
next_attempt_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
published_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
lease_until = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_attachment_jobs", x => x.id);
table.ForeignKey(
name: "fk_attachment_jobs_attachments_attachment_id",
column: x => x.attachment_id,
principalTable: "attachments",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "attachment_variants",
columns: table => new
{
attachment_id = table.Column<Guid>(type: "uuid", nullable: false),
pipeline_version = table.Column<int>(type: "integer", nullable: false),
name = table.Column<string>(type: "text", nullable: false),
object_key = table.Column<string>(type: "text", nullable: false),
content_type = table.Column<string>(type: "text", nullable: false),
width = table.Column<int>(type: "integer", nullable: false),
height = table.Column<int>(type: "integer", nullable: false),
size_bytes = table.Column<long>(type: "bigint", nullable: false),
sha256 = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("pk_attachment_variants", x => new { x.attachment_id, x.pipeline_version, x.name });
table.ForeignKey(
name: "fk_attachment_variants_attachments_attachment_id",
column: x => x.attachment_id,
principalTable: "attachments",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "ix_attachment_jobs_attachment_id",
table: "attachment_jobs",
column: "attachment_id",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_attachment_jobs_lease_until",
table: "attachment_jobs",
column: "lease_until",
filter: "lease_until IS NOT NULL");
migrationBuilder.CreateIndex(
name: "ix_attachment_jobs_next_attempt_at",
table: "attachment_jobs",
column: "next_attempt_at",
filter: "published_at IS NULL");
migrationBuilder.CreateIndex(
name: "ix_attachment_variants_object_key",
table: "attachment_variants",
column: "object_key",
unique: true);
// Старые originals уже устойчивы. Обрабатываем их на месте, сохраняя ID и ссылки сообщений.
migrationBuilder.Sql("""
INSERT INTO attachment_jobs (id, attachment_id, source_key, pipeline_version, attempt, created_at, next_attempt_at)
SELECT gen_random_uuid(), id, object_key, 1, 1, now(), now() FROM attachments WHERE status = 'ready';
UPDATE attachments SET status = 'queued', updated_at = now() WHERE status = 'ready';
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM attachments WHERE status <> 'ready') THEN
RAISE EXCEPTION 'Lab4 requires a published original for every attachment';
END IF;
END $$;
""");
migrationBuilder.DropTable(
name: "attachment_jobs");
migrationBuilder.DropTable(
name: "attachment_variants");
migrationBuilder.DropColumn(
name: "error_code",
table: "attachments");
migrationBuilder.RenameColumn(
name: "updated_at",
table: "attachments",
newName: "uploaded_at");
}
}
}
@@ -0,0 +1,593 @@
// <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("20261127163030_VersionedAttachmentJobs")]
partial class VersionedAttachmentJobs
{
/// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("ErrorCode")
.HasColumnType("text")
.HasColumnName("error_code");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<int>("PipelineVersion")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("pipeline_version");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("Attempt")
.HasColumnType("integer")
.HasColumnName("attempt");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("FirstAttempt")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("first_attempt");
b.Property<DateTimeOffset?>("LeaseUntil")
.HasColumnType("timestamp with time zone")
.HasColumnName("lease_until");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<DateTimeOffset?>("PublishedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("published_at");
b.Property<DateTimeOffset?>("ReplayedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("replayed_at");
b.Property<string>("SourceKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("source_key");
b.HasKey("Id")
.HasName("pk_attachment_jobs");
b.HasIndex("LeaseUntil")
.HasDatabaseName("ix_attachment_jobs_lease_until")
.HasFilter("lease_until IS NOT NULL");
b.HasIndex("NextAttemptAt")
.HasDatabaseName("ix_attachment_jobs_next_attempt_at")
.HasFilter("published_at IS NULL");
b.HasIndex("AttachmentId", "PipelineVersion")
.IsUnique()
.HasDatabaseName("ix_attachment_jobs_attachment_id_pipeline_version");
b.ToTable("attachment_jobs", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<string>("Name")
.HasColumnType("text")
.HasColumnName("name");
b.Property<string>("ContentType")
.IsRequired()
.HasColumnType("text")
.HasColumnName("content_type");
b.Property<int>("Height")
.HasColumnType("integer")
.HasColumnName("height");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<string>("Sha256")
.IsRequired()
.HasColumnType("text")
.HasColumnName("sha256");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<int>("Width")
.HasColumnType("integer")
.HasColumnName("width");
b.HasKey("AttachmentId", "PipelineVersion", "Name")
.HasName("pk_attachment_variants");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachment_variants_object_key");
b.ToTable("attachment_variants", (string)null);
});
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.PrimitiveCollection<Guid[]>("AttachmentIds")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("uuid[]")
.HasColumnName("attachment_ids")
.HasDefaultValueSql("'{}'::uuid[]");
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_attachment_limit", "cardinality(attachment_ids) <= 10");
t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0");
});
});
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.UploadIntentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("DeleteCount")
.HasColumnType("integer")
.HasColumnName("delete_count");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.HasKey("Id")
.HasName("pk_upload_intents");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_upload_intents_object_key");
b.HasIndex("NextAttemptAt", "ExpiresAt")
.HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at");
b.ToTable("upload_intents", (string)null);
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment")
.WithMany()
.HasForeignKey("AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_jobs_attachments_attachment_id");
b.Navigation("Attachment");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", null)
.WithMany("Variants")
.HasForeignKey("AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_variants_attachments_attachment_id");
});
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");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b =>
{
b.Navigation("Variants");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,85 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Messenger.Api.Data.Migrations
{
/// <inheritdoc />
public partial class VersionedAttachmentJobs : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "ix_attachment_jobs_attachment_id",
table: "attachment_jobs");
migrationBuilder.AddColumn<int>(
name: "pipeline_version",
table: "attachments",
type: "integer",
nullable: false,
defaultValue: 1);
migrationBuilder.AddColumn<int>(
name: "first_attempt",
table: "attachment_jobs",
type: "integer",
nullable: false,
defaultValue: 1);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "replayed_at",
table: "attachment_jobs",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.CreateIndex(
name: "ix_attachment_jobs_attachment_id_pipeline_version",
table: "attachment_jobs",
columns: new[] { "attachment_id", "pipeline_version" },
unique: true);
// Установки с ранним worker могут хранить только thumbnail. Оригинал уже в S3.
migrationBuilder.Sql("""
WITH partial AS (
UPDATE attachments a SET pipeline_version = 2, status = 'queued', updated_at = now()
WHERE status = 'ready' AND NOT EXISTS (
SELECT 1 FROM attachment_variants v WHERE v.attachment_id = a.id
AND v.pipeline_version = 1 AND v.name = 'optimized'
)
RETURNING id, object_key
)
INSERT INTO attachment_jobs (id, attachment_id, source_key, pipeline_version, attempt, created_at, next_attempt_at)
SELECT gen_random_uuid(), id, object_key, 2, 1, now(), now() FROM partial;
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "ix_attachment_jobs_attachment_id_pipeline_version",
table: "attachment_jobs");
migrationBuilder.DropColumn(
name: "pipeline_version",
table: "attachments");
migrationBuilder.DropColumn(
name: "first_attempt",
table: "attachment_jobs");
migrationBuilder.DropColumn(
name: "replayed_at",
table: "attachment_jobs");
migrationBuilder.CreateIndex(
name: "ix_attachment_jobs_attachment_id",
table: "attachment_jobs",
column: "attachment_id",
unique: true);
}
}
}
@@ -0,0 +1,590 @@
// <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.AttachmentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("ChatId")
.HasColumnType("uuid")
.HasColumnName("chat_id");
b.Property<string>("ChecksumSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("checksum_sha256");
b.Property<string>("ContentType")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("content_type");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("ErrorCode")
.HasColumnType("text")
.HasColumnName("error_code");
b.Property<string>("Filename")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("filename");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<Guid>("OwnerId")
.HasColumnType("uuid")
.HasColumnName("owner_id");
b.Property<int>("PipelineVersion")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("pipeline_version");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.HasKey("Id")
.HasName("pk_attachments");
b.HasIndex("ChatId")
.HasDatabaseName("ix_attachments_chat_id");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachments_object_key");
b.HasIndex("OwnerId")
.HasDatabaseName("ix_attachments_owner_id");
b.ToTable("attachments", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("Attempt")
.HasColumnType("integer")
.HasColumnName("attempt");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("FirstAttempt")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("first_attempt");
b.Property<DateTimeOffset?>("LeaseUntil")
.HasColumnType("timestamp with time zone")
.HasColumnName("lease_until");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<DateTimeOffset?>("PublishedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("published_at");
b.Property<DateTimeOffset?>("ReplayedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("replayed_at");
b.Property<string>("SourceKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("source_key");
b.HasKey("Id")
.HasName("pk_attachment_jobs");
b.HasIndex("LeaseUntil")
.HasDatabaseName("ix_attachment_jobs_lease_until")
.HasFilter("lease_until IS NOT NULL");
b.HasIndex("NextAttemptAt")
.HasDatabaseName("ix_attachment_jobs_next_attempt_at")
.HasFilter("published_at IS NULL");
b.HasIndex("AttachmentId", "PipelineVersion")
.IsUnique()
.HasDatabaseName("ix_attachment_jobs_attachment_id_pipeline_version");
b.ToTable("attachment_jobs", (string)null);
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.Property<Guid>("AttachmentId")
.HasColumnType("uuid")
.HasColumnName("attachment_id");
b.Property<int>("PipelineVersion")
.HasColumnType("integer")
.HasColumnName("pipeline_version");
b.Property<string>("Name")
.HasColumnType("text")
.HasColumnName("name");
b.Property<string>("ContentType")
.IsRequired()
.HasColumnType("text")
.HasColumnName("content_type");
b.Property<int>("Height")
.HasColumnType("integer")
.HasColumnName("height");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.Property<string>("Sha256")
.IsRequired()
.HasColumnType("text")
.HasColumnName("sha256");
b.Property<long>("SizeBytes")
.HasColumnType("bigint")
.HasColumnName("size_bytes");
b.Property<int>("Width")
.HasColumnType("integer")
.HasColumnName("width");
b.HasKey("AttachmentId", "PipelineVersion", "Name")
.HasName("pk_attachment_variants");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_attachment_variants_object_key");
b.ToTable("attachment_variants", (string)null);
});
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.PrimitiveCollection<Guid[]>("AttachmentIds")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("uuid[]")
.HasColumnName("attachment_ids")
.HasDefaultValueSql("'{}'::uuid[]");
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_attachment_limit", "cardinality(attachment_ids) <= 10");
t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0");
});
});
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.UploadIntentEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<int>("DeleteCount")
.HasColumnType("integer")
.HasColumnName("delete_count");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<DateTimeOffset>("NextAttemptAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("next_attempt_at");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text")
.HasColumnName("object_key");
b.HasKey("Id")
.HasName("pk_upload_intents");
b.HasIndex("ObjectKey")
.IsUnique()
.HasDatabaseName("ix_upload_intents_object_key");
b.HasIndex("NextAttemptAt", "ExpiresAt")
.HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at");
b.ToTable("upload_intents", (string)null);
});
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.AttachmentEntity", b =>
{
b.HasOne("Messenger.Api.Data.ChatEntity", null)
.WithMany()
.HasForeignKey("ChatId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_chats_chat_id");
b.HasOne("Messenger.Api.Data.UserEntity", null)
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("fk_attachments_users_owner_id");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment")
.WithMany()
.HasForeignKey("AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_jobs_attachments_attachment_id");
b.Navigation("Attachment");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b =>
{
b.HasOne("Messenger.Api.Data.AttachmentEntity", null)
.WithMany("Variants")
.HasForeignKey("AttachmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasConstraintName("fk_attachment_variants_attachments_attachment_id");
});
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");
});
modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b =>
{
b.Navigation("Variants");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,176 @@
using System.Security.Cryptography;
using Messenger.Api.Data;
using Messenger.Api.Models;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
using StbImageSharp;
namespace Messenger.Api.Endpoints;
public static class AttachmentEndpoints
{
public static IEndpointRouteBuilder MapAttachmentEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapPost("/api/v1/chats/{chatId}/attachments", Upload).RequireAuthorization();
endpoints.MapGet("/api/v1/attachments/{attachmentId}", Metadata).RequireAuthorization();
endpoints.MapGet("/api/v1/attachments/{attachmentId}/content", Content).RequireAuthorization();
return endpoints;
}
private static async Task<IResult> Upload(Guid chatId, HttpContext http, MessengerDbContext db,
IAttachmentStorage storage, UploadSettings limits, UploadGate gate, UploadCleanupSettings cleanup)
{
var user = http.GetUserId();
if (!await db.ChatMembers.AnyAsync(m => m.ChatId == chatId && m.UserId == user, http.RequestAborted))
return ApiErrors.Error(http, 404, "not_found", "Объект не найден");
var names = http.Request.Query["filename"];
var name = names.Count == 1 ? names[0] : null;
if (string.IsNullOrWhiteSpace(name) || ApiErrors.CodePoints(name) > 255 ||
name.Any(c => c is '/' or '\\' || char.IsControl(c)))
return ApiErrors.Error(http, 400, "invalid_request", "Некорректное имя файла");
var mime = http.Request.ContentType?.Split(';', 2)[0].Trim().ToLowerInvariant();
if (mime is not ("image/png" or "image/jpeg"))
return ApiErrors.Error(http, 415, "unsupported_media_type", "Требуется PNG или JPEG");
if (http.Request.ContentLength > limits.MaxBytes)
return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
var ct = timeout.Token;
if (!await gate.Slots.WaitAsync(TimeSpan.FromSeconds(2), ct))
return ApiErrors.Error(http, 503, "unavailable", "Загрузка временно перегружена");
try
{
// Временный файл ограничивает память API при приёме HTTP-тела.
var path = Path.Combine(Path.GetTempPath(), $"attachment-{Guid.NewGuid():N}");
await using var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
65536, FileOptions.Asynchronous | FileOptions.DeleteOnClose);
var buffer = new byte[65536];
long size = 0;
while (true)
{
var count = await http.Request.Body.ReadAsync(buffer, ct);
if (count == 0) break;
size += count;
if (size > limits.MaxBytes)
return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера");
await file.WriteAsync(buffer.AsMemory(0, count), ct);
}
file.Position = 0;
try
{
var signature = new byte[8];
if (size < 12) throw new InvalidDataException("Truncated image");
await file.ReadExactlyAsync(signature, ct);
var actual = signature.AsSpan().SequenceEqual(new byte[] {137,80,78,71,13,10,26,10}) ? "image/png" :
signature[0] == 255 && signature[1] == 216 ? "image/jpeg" : "unknown";
if (actual != mime)
return ApiErrors.Error(http, 415, "unsupported_media_type", "Содержимое не соответствует MIME");
file.Position = 0;
var info = ImageInfo.FromStream(file) ?? throw new InvalidDataException("Invalid image header");
if (info.Width <= 0 || info.Height <= 0) throw new InvalidDataException("Invalid dimensions");
if ((long)info.Width * info.Height > limits.MaxPixels)
return ApiErrors.Error(http, 413, "payload_too_large", "Слишком много пикселей");
if (mime == "image/png") await PngIntegrity.ValidateAsync(file,
(long)info.Width * info.Height * 8 + info.Height * 8L + 1024, ct);
// Декодеры могут принимать обрезанные JPEG: обязательно проверяем окончание файла.
var tail = new byte[12];
if (size < tail.Length) throw new InvalidDataException("Truncated image");
file.Position = size - tail.Length;
await file.ReadExactlyAsync(tail, ct);
if (mime == "image/png" && !tail.AsSpan().SequenceEqual(new byte[] { 0,0,0,0,73,69,78,68,174,66,96,130 }) ||
mime == "image/jpeg" && (tail[^2] != 255 || tail[^1] != 217))
throw new InvalidDataException("Truncated image");
}
catch (Exception ex) when (ex is InvalidDataException or EndOfStreamException or InvalidOperationException or ArgumentException or IndexOutOfRangeException)
{
return ApiErrors.Error(http, 415, "unsupported_media_type", "Повреждённое изображение");
}
file.Position = 0;
var hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, ct));
var id = Guid.CreateVersion7();
var now = Timestamps.UtcNowMilliseconds();
var entity = new AttachmentEntity
{
Id = id, ChatId = chatId, OwnerId = user, Filename = name!, ContentType = mime!,
ObjectKey = $"originals/{id:N}", SizeBytes = size, ChecksumSha256 = hash,
Status = "queued", CreatedAt = now, UpdatedAt = now
};
var intent = new UploadIntentEntity
{
Id = id, ObjectKey = $"staging/{id:N}", CreatedAt = now,
ExpiresAt = now + cleanup.Grace, NextAttemptAt = now + cleanup.Grace
};
db.UploadIntents.Add(intent);
await db.SaveChangesAsync(ct); // S3 PUT не начинается без устойчивого журнала.
file.Position = 0;
await storage.PutAsync(intent.ObjectKey, file, entity.ContentType, ct);
await using var tx = await db.Database.BeginTransactionAsync(ct);
var activeIntent = await db.UploadIntents.FromSqlInterpolated($"""
SELECT * FROM upload_intents WHERE id = {id} AND expires_at > clock_timestamp() FOR UPDATE
""").SingleOrDefaultAsync(ct);
if (activeIntent is null)
return ApiErrors.Error(http, 503, "unavailable", "Время публикации вложения истекло");
db.Attachments.Add(entity);
db.AttachmentJobs.Add(new AttachmentJobEntity
{
Id = Guid.CreateVersion7(), AttachmentId = id, SourceKey = intent.ObjectKey,
CreatedAt = now, NextAttemptAt = now
});
db.UploadIntents.Remove(activeIntent);
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
// Возвращаем снимок приёма даже если worker уже успел закончить.
return Results.Accepted($"/api/v1/attachments/{id}", ToDto(entity));
}
catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested)
{
return ApiErrors.Error(http, 503, "unavailable", "Истекло время загрузки");
}
finally { gate.Slots.Release(); }
}
private static Task<AttachmentEntity?> Find(Guid id, HttpContext http, MessengerDbContext db) =>
db.Attachments.AsNoTracking().Include(a => a.Variants).FirstOrDefaultAsync(a => a.Id == id &&
db.ChatMembers.Any(m => m.ChatId == a.ChatId && m.UserId == http.GetUserId()), http.RequestAborted);
private static async Task<IResult> Metadata(Guid attachmentId, HttpContext http, MessengerDbContext db)
{
var entity = await Find(attachmentId, http, db);
return entity is null ? ApiErrors.Error(http, 404, "not_found", "Объект не найден") : Results.Ok(ToDto(entity));
}
private static async Task<IResult> Content(Guid attachmentId, HttpContext http, MessengerDbContext db,
IAttachmentStorage storage, string? variant)
{
var entity = await Find(attachmentId, http, db);
if (entity is null) return ApiErrors.Error(http, 404, "not_found", "Объект не найден");
if (entity.Status != "ready") return ApiErrors.Error(http, 409, "conflict", "Вложение не готово");
var (key, mime, size, hash) = (entity.ObjectKey, entity.ContentType, entity.SizeBytes, entity.ChecksumSha256);
if (variant is not (null or "original"))
{
var selected = entity.Variants.SingleOrDefault(v => v.PipelineVersion == entity.PipelineVersion && v.Name == variant);
if (selected is null) return ApiErrors.Error(http, 404, "not_found", "Вариант не найден");
(key, mime, size, hash) = (selected.ObjectKey, selected.ContentType, selected.SizeBytes, selected.Sha256);
}
// Ограниченный 10 MiB буфер до начала ответа позволяет честно вернуть 503 при отказе S3.
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
using var output = new LimitedDownloadStream(Math.Min(size, 10485760));
try { await storage.CopyToAsync(key, output, timeout.Token); }
catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested)
{ return ApiErrors.Error(http, 503, "unavailable", "Истекло время скачивания"); }
catch (IOException) { return ApiErrors.Error(http, 503, "unavailable", "Ошибка чтения объекта"); }
if (output.Length != size ||
Convert.ToHexStringLower(SHA256.HashData(output.GetBuffer().AsSpan(0, (int)output.Length))) != hash)
return ApiErrors.Error(http, 503, "unavailable", "Объект не соответствует метаданным");
http.Response.Headers["X-Content-Type-Options"] = "nosniff";
return Results.File(output.ToArray(), mime);
}
private static Attachment ToDto(AttachmentEntity a) => new(a.Id, a.ChatId, a.OwnerId, a.Filename,
a.ContentType, a.SizeBytes, a.ChecksumSha256, a.Status,
a.Variants.Where(v => a.Status == "ready" && v.PipelineVersion == a.PipelineVersion)
.OrderBy(v => v.Name).Select(v => new AttachmentVariant(v.Name, v.ContentType, v.SizeBytes, v.Width, v.Height, v.Sha256)).ToArray(),
a.ErrorCode, a.CreatedAt, a.UpdatedAt ?? a.CreatedAt);
}
@@ -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,244 @@
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 (request.AttachmentIds is null || request.AttachmentIds.Length > 10 ||
request.AttachmentIds.Distinct().Count() != request.AttachmentIds.Length ||
(string.IsNullOrWhiteSpace(request.Text) && request.AttachmentIds.Length == 0) ||
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, request.AttachmentIds), 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));
}
if (request.AttachmentIds.Length > 0)
{
// Блокировка до COMMIT упорядочивает отправку сообщения и переход вложения в failed.
var attachments = await db.Attachments.FromSql($"""
SELECT * FROM attachments WHERE chat_id = {chatId} AND id = ANY({request.AttachmentIds})
ORDER BY id FOR SHARE
""").AsNoTracking().ToListAsync(ct);
if (attachments.Count != request.AttachmentIds.Length)
return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден");
if (attachments.Any(a => a.Status == "failed"))
return ApiErrors.Error(httpContext, 409, "conflict", "Обработка вложения завершилась ошибкой");
}
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,
AttachmentIds = request.AttachmentIds,
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 = $"hist4:{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,
AttachmentIds = m.AttachmentIds
};
}
@@ -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);
}
}
+75
View File
@@ -0,0 +1,75 @@
using Messenger.Api.Data;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
namespace Messenger.Api.Jobs;
public sealed record JobSettings(int MaxAttempts, TimeSpan Timeout, int Concurrency, TimeSpan FailedRetention)
{
public static JobSettings From(IConfiguration config)
{
var attempts = config.GetValue("JOB_MAX_ATTEMPTS", 5);
var timeout = config.GetValue("JOB_TIMEOUT_SECONDS", 60);
var concurrency = config.GetValue("WORKER_CONCURRENCY", 2);
var retention = config.GetValue("STAGING_RETENTION_SECONDS", 86400);
if (attempts < 1 || timeout < 1 || concurrency < 1 || retention < 0)
throw new InvalidOperationException("Некорректные настройки обработки вложений");
return new(attempts, TimeSpan.FromSeconds(timeout), concurrency, TimeSpan.FromSeconds(retention));
}
}
public sealed record JobMessage(int SchemaVersion, Guid JobId, string Type, Guid AttachmentId,
int PipelineVersion, int Attempt, DateTimeOffset CreatedAt)
{
public const string ProcessType = "attachment.process.v1";
public static JobMessage From(AttachmentJobEntity job) =>
new(1, job.Id, ProcessType, job.AttachmentId, job.PipelineVersion, job.Attempt, job.CreatedAt);
}
internal static class AttachmentJobs
{
// Все изменения состояния используют один порядок блокировок: сначала job, затем attachment.
public static async Task<AttachmentJobEntity?> LockAsync(MessengerDbContext db, Guid id, CancellationToken ct)
{
var job = await db.AttachmentJobs.FromSql($"SELECT * FROM attachment_jobs WHERE id = {id} FOR UPDATE")
.SingleOrDefaultAsync(ct);
if (job is not null)
job.Attachment = await LockAttachmentAsync(db, job.AttachmentId, ct);
return job;
}
public static Task<AttachmentEntity> LockAttachmentAsync(MessengerDbContext db, Guid id, CancellationToken ct) =>
db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE").SingleAsync(ct);
public static void FailAttempt(MessengerDbContext db, AttachmentJobEntity job, JobSettings settings,
string code, bool permanent)
{
var now = Timestamps.UtcNowMilliseconds();
job.LeaseUntil = null;
job.Attachment.UpdatedAt = now;
var used = job.Attempt - job.FirstAttempt + 1;
if (permanent || used >= settings.MaxAttempts)
{
job.Attachment.Status = "failed";
job.Attachment.ErrorCode = permanent ? code : "retry_exhausted";
ScheduleCleanup(db, job, now + settings.FailedRetention);
return;
}
job.Attempt++;
job.Attachment.Status = "queued";
var delay = Math.Min(30, Math.Pow(2, used - 1));
job.NextAttemptAt = now.AddSeconds(delay + Random.Shared.NextDouble() * delay * 0.25);
job.PublishedAt = null;
}
public static void ScheduleCleanup(MessengerDbContext db, AttachmentJobEntity job, DateTimeOffset after)
{
// При переносе из ЛР4 источником служит сам постоянный оригинал.
if (job.SourceKey != $"staging/{job.AttachmentId:N}") return;
db.UploadIntents.Add(new UploadIntentEntity
{
Id = job.AttachmentId, ObjectKey = job.SourceKey, CreatedAt = Timestamps.UtcNowMilliseconds(),
ExpiresAt = after, NextAttemptAt = after
});
}
}
@@ -0,0 +1,108 @@
using System.Security.Cryptography;
using Messenger.Api.Data;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
namespace Messenger.Api.Jobs;
public sealed class AttachmentProcessor(MessengerDbContext db, IAttachmentStorage storage,
JobSettings settings, UploadSettings limits, ILogger<AttachmentProcessor> logger)
{
public async Task ProcessAsync(JobMessage message, CancellationToken stopping)
{
var job = await ClaimAsync(message, stopping);
if (job is null) return;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stopping);
deadline.CancelAfter(settings.Timeout);
var ct = deadline.Token;
try
{
var attachment = job.Attachment;
JobFaultInjection.At("transient", attachment.Id);
using var original = new LimitedDownloadStream(Math.Min(attachment.SizeBytes, limits.MaxBytes));
await storage.CopyToAsync(job.SourceKey, original, ct);
original.Position = 0;
if (original.Length != attachment.SizeBytes ||
Convert.ToHexStringLower(await SHA256.HashDataAsync(original, ct)) != attachment.ChecksumSha256)
throw new InvalidDataException("Source checksum mismatch");
var variants = await ImageRenderer.RenderAsync(original, attachment.ContentType, limits.MaxPixels, message.PipelineVersion, ct);
ct.ThrowIfCancellationRequested();
await PublishResultAsync(message, original, variants, ct);
}
catch (Exception ex) when (!stopping.IsCancellationRequested)
{
logger.LogWarning("Job {JobId} attempt {Attempt} failed ({Kind})",
message.JobId, message.Attempt, ex.GetType().Name);
db.ChangeTracker.Clear();
await using var tx = await db.Database.BeginTransactionAsync(stopping);
var current = await AttachmentJobs.LockAsync(db, message.JobId, stopping);
if (OwnsAttempt(current, message))
{
var permanent = ex is InvalidDataException;
AttachmentJobs.FailAttempt(db, current!, settings, "invalid_image", permanent);
await db.SaveChangesAsync(stopping);
}
await tx.CommitAsync(stopping);
}
}
private async Task<AttachmentJobEntity?> ClaimAsync(JobMessage message, CancellationToken ct)
{
await using var tx = await db.Database.BeginTransactionAsync(ct);
var job = await AttachmentJobs.LockAsync(db, message.JobId, ct);
if (job is null || job.AttachmentId != message.AttachmentId || job.PipelineVersion != message.PipelineVersion ||
job.Attempt != message.Attempt || job.Attachment.PipelineVersion != message.PipelineVersion ||
job.Attachment.Status != "queued")
return null;
var now = Timestamps.UtcNowMilliseconds();
job.Attachment.Status = "processing";
job.Attachment.UpdatedAt = now;
job.PublishedAt ??= now;
job.LeaseUntil = now + settings.Timeout;
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
return job;
}
private static bool OwnsAttempt(AttachmentJobEntity? job, JobMessage message) =>
job is not null && job.Attempt == message.Attempt && job.Attachment.PipelineVersion == message.PipelineVersion &&
job.Attachment.Status == "processing";
private async Task PublishResultAsync(JobMessage message, Stream original, ImageVariant[] variants, CancellationToken ct)
{
db.ChangeTracker.Clear();
await using var tx = await db.Database.BeginTransactionAsync(ct);
var job = await AttachmentJobs.LockAsync(db, message.JobId, ct);
if (!OwnsAttempt(job, message)) return;
var attachment = job!.Attachment;
JobFaultInjection.At("before-write", attachment.Id);
// Устаревшая попытка не может писать в S3 после захвата работы другой попыткой.
if (job.SourceKey != attachment.ObjectKey)
{
original.Position = 0;
await storage.PutAsync(attachment.ObjectKey, original, attachment.ContentType, ct, createOnly: true);
}
foreach (var variant in variants)
{
var extension = variant.ContentType == "image/webp" ? "webp" : "jpg";
var key = $"variants/{attachment.Id:N}/v{job.PipelineVersion}/{variant.Name}.{extension}";
using var file = new MemoryStream(variant.Bytes, writable: false);
await storage.PutAsync(key, file, variant.ContentType, ct, createOnly: true);
db.AttachmentVariants.Add(new AttachmentVariantEntity
{
AttachmentId = attachment.Id, PipelineVersion = job.PipelineVersion, Name = variant.Name,
ObjectKey = key, ContentType = variant.ContentType, Width = variant.Width, Height = variant.Height,
SizeBytes = file.Length, Sha256 = Convert.ToHexStringLower(SHA256.HashData(variant.Bytes))
});
}
JobFaultInjection.At("after-write", attachment.Id);
var now = Timestamps.UtcNowMilliseconds();
attachment.Status = "ready";
attachment.UpdatedAt = now;
job.LeaseUntil = null;
AttachmentJobs.ScheduleCleanup(db, job, now);
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
}
+99
View File
@@ -0,0 +1,99 @@
using System.Text.Json;
using Messenger.Api.Data;
using Microsoft.EntityFrameworkCore;
using RabbitMQ.Client;
namespace Messenger.Api.Jobs;
internal sealed class AttachmentQueue(ConnectionFactory connections, IServiceScopeFactory scopes,
JobSettings settings, bool publisher, ILogger<AttachmentQueue> logger) : BackgroundService
{
internal const string QueueName = "attachments.v1";
private static readonly JsonSerializerOptions WireFormat = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Task.WhenAll(Enumerable.Range(0, publisher ? 1 : settings.Concurrency).Select(_ => RunChannelAsync(stoppingToken)));
private async Task RunChannelAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var connection = await connections.CreateConnectionAsync(ct);
var options = new CreateChannelOptions(publisherConfirmationsEnabled: publisher,
publisherConfirmationTrackingEnabled: publisher);
await using var channel = await connection.CreateChannelAsync(options, ct);
await channel.QueueDeclareAsync(QueueName, durable: true, exclusive: false, autoDelete: false,
arguments: new Dictionary<string, object?> { ["x-queue-type"] = "classic" }, cancellationToken: ct);
while (channel.IsOpen && !ct.IsCancellationRequested)
{
var didWork = publisher ? await PublishNextAsync(channel, ct) : await ConsumeNextAsync(channel, ct);
if (!didWork) await Task.Delay(400, ct);
}
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
// Закрытие канала возвращает брокеру все доставки, которым worker ещё не послал ack.
logger.LogWarning("Attachment queue reconnecting after {Kind}", ex.GetType().Name);
await Task.Delay(TimeSpan.FromSeconds(2), ct);
}
}
}
private async Task<bool> PublishNextAsync(IChannel channel, CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
await using var tx = await db.Database.BeginTransactionAsync(ct);
var job = await db.AttachmentJobs.FromSqlRaw("""
SELECT * FROM attachment_jobs
WHERE (published_at IS NULL AND next_attempt_at <= clock_timestamp())
OR lease_until <= clock_timestamp()
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
""").SingleOrDefaultAsync(ct);
if (job is null) return false;
if (job.LeaseUntil.HasValue)
{
job.Attachment = await AttachmentJobs.LockAttachmentAsync(db, job.AttachmentId, ct);
AttachmentJobs.FailAttempt(db, job, settings, "processing_timeout", permanent: false);
}
else
{
JobFaultInjection.At("before-publish", job.AttachmentId);
var payload = JsonSerializer.SerializeToUtf8Bytes(JobMessage.From(job), WireFormat);
var properties = new BasicProperties { Persistent = true, ContentType = "application/json", MessageId = job.Id.ToString() };
using var confirm = CancellationTokenSource.CreateLinkedTokenSource(ct);
confirm.CancelAfter(TimeSpan.FromSeconds(5));
await channel.BasicPublishAsync("", QueueName, mandatory: true, properties, payload, confirm.Token);
job.PublishedAt = DateTimeOffset.UtcNow;
}
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
return true;
}
private async Task<bool> ConsumeNextAsync(IChannel channel, CancellationToken ct)
{
// Один неподтверждённый файл на канал. Каждый параллельный обработчик имеет собственный канал.
var delivery = await channel.BasicGetAsync(QueueName, autoAck: false, ct);
if (delivery is null) return false;
JobMessage? message;
try { message = JsonSerializer.Deserialize<JobMessage>(delivery.Body.Span, WireFormat); }
catch (JsonException) { message = null; }
if (message is not { SchemaVersion: 1, Type: JobMessage.ProcessType, PipelineVersion: 1 or 2, Attempt: >= 1 } ||
message.JobId == Guid.Empty || message.AttachmentId == Guid.Empty || message.CreatedAt == default)
{
logger.LogWarning("Discarded malformed attachment job");
await channel.BasicRejectAsync(delivery.DeliveryTag, requeue: false, ct);
return true;
}
using var scope = scopes.CreateScope();
await scope.ServiceProvider.GetRequiredService<AttachmentProcessor>().ProcessAsync(message, ct);
JobFaultInjection.At("before-ack", message.AttachmentId, message.Attempt);
await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false, ct);
logger.LogInformation("Ack job {JobId} attempt {Attempt} redelivered {Redelivered}",
message.JobId, message.Attempt, delivery.Redelivered);
return true;
}
}
+79
View File
@@ -0,0 +1,79 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using ImageMagick;
using Messenger.Api.Services;
namespace Messenger.Api.Jobs;
internal static class ImageRenderer
{
public static async Task<ImageVariant[]> RenderAsync(Stream input, string mime, long maxPixels, int version,
CancellationToken ct)
{
// Нативное декодирование выполняется в дочернем процессе, который можно завершить по дедлайну.
var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
{
RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false
};
start.ArgumentList.Add(typeof(ImageRenderer).Assembly.Location);
start.ArgumentList.Add("--render-attachment");
start.ArgumentList.Add(mime);
start.ArgumentList.Add(maxPixels.ToString(CultureInfo.InvariantCulture));
start.ArgumentList.Add(version.ToString(CultureInfo.InvariantCulture));
using var process = Process.Start(start) ?? throw new IOException("Cannot start image renderer");
try
{
var response = process.StandardOutput.ReadToEndAsync(ct);
input.Position = 0;
try
{
await input.CopyToAsync(process.StandardInput.BaseStream, ct);
process.StandardInput.Close();
}
catch (IOException)
{
// Дочерний процесс может завершиться до окончания передачи.
process.StandardInput.Close();
}
await process.WaitForExitAsync(ct);
var json = await response;
return process.ExitCode switch
{
0 => JsonSerializer.Deserialize<ImageVariant[]>(json) ?? throw new IOException("Empty renderer result"),
2 => throw new InvalidDataException("Invalid image"),
_ => throw new IOException($"Image renderer exit code {process.ExitCode}")
};
}
finally
{
if (!process.HasExited)
{
try { process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { }
await process.WaitForExitAsync();
}
}
}
public static async Task<int> RunAsync(string mime, long maxPixels, int version)
{
try
{
using var original = new LimitedDownloadStream(10485760);
await Console.OpenStandardInput().CopyToAsync(original);
var result = ImageVariant.CreateAll(original, mime, maxPixels, version);
await JsonSerializer.SerializeAsync(Console.OpenStandardOutput(), result);
return 0;
}
catch (Exception ex) when (ex is InvalidDataException or MagickCorruptImageErrorException or MagickCoderErrorException)
{
return 2;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Image renderer: {ex.GetType().Name}");
return 3;
}
}
}
+59
View File
@@ -0,0 +1,59 @@
using ImageMagick;
using StbImageSharp;
namespace Messenger.Api.Jobs;
public sealed record ImageVariant(string Name, string ContentType, byte[] Bytes, int Width, int Height)
{
public static ImageVariant[] CreateAll(Stream original, string mime, long maxPixels, int version)
{
if (version is not (1 or 2) || mime is not ("image/png" or "image/jpeg"))
throw new InvalidDataException("Unsupported image or pipeline version");
original.Position = 0;
var header = ImageInfo.FromStream(original);
if (header is null || header.Value.Width <= 0 || header.Value.Height <= 0 ||
(long)header.Value.Width * header.Value.Height > maxPixels)
throw new InvalidDataException("Invalid image dimensions");
original.Position = 0;
var read = new MagickReadSettings
{
Format = mime == "image/png" ? MagickFormat.Png : MagickFormat.Jpeg, FrameCount = 1
};
using var image = new MagickImage(original, read);
if (image.Width != header.Value.Width || image.Height != header.Value.Height)
throw new InvalidDataException("Image dimensions changed during decode");
image.AutoOrient();
image.Strip();
using var thumbnail = image.Clone();
Fit(thumbnail, 256);
using var crop = image.Clone();
var side = Math.Min(crop.Width, crop.Height);
crop.Crop(side, side, Gravity.Center);
crop.ResetPage();
crop.Resize(128, 128);
Fit(image, 1280);
image.Quality = version == 1 ? 78u : 86u;
return [EncodeJpeg(thumbnail, "thumbnail", version == 1 ? 85u : 92u),
EncodeJpeg(crop, "crop", 85),
new ImageVariant("optimized", "image/webp", image.ToByteArray(MagickFormat.WebP), (int)image.Width, (int)image.Height)];
}
private static void Fit(IMagickImage<byte> image, uint limit)
{
var longest = Math.Max(image.Width, image.Height);
if (longest <= limit) return;
var width = (uint)Math.Max(1L, image.Width * (long)limit / longest);
var height = (uint)Math.Max(1L, image.Height * (long)limit / longest);
image.Resize(new MagickGeometry(width, height) { IgnoreAspectRatio = true });
}
private static ImageVariant EncodeJpeg(IMagickImage<byte> image, string name, uint quality)
{
image.BackgroundColor = MagickColors.White;
image.Alpha(AlphaAction.Remove);
image.Quality = quality;
return new(name, "image/jpeg", image.ToByteArray(MagickFormat.Jpeg), (int)image.Width, (int)image.Height);
}
}
@@ -0,0 +1,13 @@
namespace Messenger.Api.Jobs;
internal static class JobFaultInjection
{
public static void At(string stage, Guid attachmentId, int? attempt = null)
{
var target = attempt is null ? $"{stage}:{attachmentId:D}" : $"{stage}:{attachmentId:D}:{attempt}";
if (Environment.GetEnvironmentVariable("LAB5_TEST_FAULT") != target) return;
Console.Error.WriteLine($"Injected fault {stage} for {attachmentId:D}");
if (stage == "transient") throw new IOException("Injected storage error");
Environment.Exit(71);
}
}
+85
View File
@@ -0,0 +1,85 @@
using Messenger.Api.Data;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
namespace Messenger.Api.Jobs;
internal static class JobOperations
{
public static async Task<int> RunAsync(string action, Guid id = default)
{
var config = Host.CreateApplicationBuilder().Configuration;
var options = new DbContextOptionsBuilder<MessengerDbContext>()
.UseNpgsql(DatabaseSettings.From(config).ConnectionString).UseSnakeCaseNamingConvention().Options;
await using var db = new MessengerDbContext(options);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var ct = timeout.Token;
if (action == "--failed-jobs")
{
var failed = await db.AttachmentJobs.Where(j => j.Attachment.Status == "failed" &&
j.Attachment.PipelineVersion == j.PipelineVersion).OrderByDescending(j => j.Attachment.UpdatedAt)
.Take(100).Select(j => new { j.Id, j.AttachmentId, j.PipelineVersion, j.Attempt, j.Attachment.ErrorCode }).ToListAsync(ct);
foreach (var job in failed)
Console.WriteLine($"{job.Id} attachment={job.AttachmentId} version={job.PipelineVersion} attempt={job.Attempt} code={job.ErrorCode}");
return 0;
}
await using var tx = await db.Database.BeginTransactionAsync(ct);
var now = Timestamps.UtcNowMilliseconds();
if (action == "--replay-job")
{
var job = await AttachmentJobs.LockAsync(db, id, ct);
if (job is null || job.Attachment.Status != "failed" || job.Attachment.PipelineVersion != job.PipelineVersion)
return Reject("Job must be the failed current version");
if (job.SourceKey != job.Attachment.ObjectKey)
{
var intent = await db.UploadIntents.FromSql($"""
SELECT * FROM upload_intents WHERE id = {job.AttachmentId}
AND expires_at > clock_timestamp() FOR UPDATE
""").SingleOrDefaultAsync(ct);
if (intent is null) return Reject("The staged original is outside its retention window");
db.UploadIntents.Remove(intent);
}
job.Attempt = checked(job.Attempt + 1);
job.FirstAttempt = job.Attempt;
job.ReplayedAt = now;
job.NextAttemptAt = now;
job.PublishedAt = null;
SetQueued(job.Attachment, now);
}
else
{
var attachment = await db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE")
.SingleOrDefaultAsync(ct);
if (attachment is not { Status: "ready", PipelineVersion: 1 })
return Reject("Version 2 requires a ready version 1");
attachment.PipelineVersion = 2;
SetQueued(attachment, now);
var job = new AttachmentJobEntity
{
Id = Guid.CreateVersion7(), AttachmentId = id, PipelineVersion = 2, SourceKey = attachment.ObjectKey,
CreatedAt = now, NextAttemptAt = now
};
db.AttachmentJobs.Add(job);
id = job.Id;
}
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
Console.WriteLine($"Queued job {id}");
return 0;
}
private static void SetQueued(AttachmentEntity attachment, DateTimeOffset now)
{
attachment.Status = "queued";
attachment.ErrorCode = null;
attachment.UpdatedAt = now;
}
private static int Reject(string message)
{
Console.Error.WriteLine(message);
return 2;
}
}
+37
View File
@@ -0,0 +1,37 @@
using Messenger.Api.Data;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
using RabbitMQ.Client;
namespace Messenger.Api.Jobs;
internal static class QueueHost
{
public static async Task RunAsync(bool publisher)
{
var builder = Host.CreateApplicationBuilder();
var config = builder.Configuration;
var urlFile = config["BROKER_URL_FILE"] ?? throw new InvalidOperationException("BROKER_URL_FILE не задан");
var connections = new ConnectionFactory
{
Uri = new Uri(File.ReadAllText(urlFile).Trim()), AutomaticRecoveryEnabled = false,
RequestedConnectionTimeout = TimeSpan.FromSeconds(5)
};
var settings = JobSettings.From(config);
var database = DatabaseSettings.From(config);
builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
builder.Services.AddSingleton(settings);
builder.Services.AddDbContext<MessengerDbContext>(options =>
options.UseNpgsql(database.ConnectionString).UseSnakeCaseNamingConvention());
if (!publisher)
{
builder.Services.AddSingleton(UploadSettings.From(config));
builder.Services.AddSingleton<IAttachmentStorage>(_ => new S3AttachmentStorage(S3Settings.From(config)));
builder.Services.AddScoped<AttachmentProcessor>();
}
builder.Services.AddHostedService(sp => new AttachmentQueue(connections,
sp.GetRequiredService<IServiceScopeFactory>(), settings, publisher, sp.GetRequiredService<ILogger<AttachmentQueue>>()));
using var host = builder.Build();
await host.RunAsync();
}
}
+29
View File
@@ -0,0 +1,29 @@
<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="AWSSDK.S3" Version="4.1.0" />
<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="RabbitMQ.Client" Version="7.1.2" />
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="15.1.1" />
<PackageReference Include="StbImageSharp" Version="2.30.16" />
<PackageReference Include="StackExchange.Redis" Version="3.4.20" />
</ItemGroup>
</Project>
+9
View File
@@ -0,0 +1,9 @@
namespace Messenger.Api.Models;
public sealed record Attachment(
Guid Id, Guid ChatId, Guid OwnerId, string Filename, string ContentType,
long SizeBytes, string Sha256, string Status, AttachmentVariant[] Variants,
string? ErrorCode, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt);
public sealed record AttachmentVariant(string Name, string ContentType, long SizeBytes,
int Width, int Height, string Sha256);
+14
View File
@@ -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,6 @@
namespace Messenger.Api.Models;
public sealed record CreateMessageRequest([property: System.Text.Json.Serialization.JsonRequired] string Text)
{
public Guid[] AttachmentIds { get; init; } = [];
}
@@ -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);
}
+17
View File
@@ -0,0 +1,17 @@
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; }
public Guid[] AttachmentIds { get; init; } = [];
}
}
@@ -0,0 +1,7 @@
namespace Messenger.Api.Models;
public sealed record SessionResponse(
string Token,
string TokenType,
DateTimeOffset ExpiresAt,
User User);
+14
View File
@@ -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; }
}
}
+295
View File
@@ -0,0 +1,295 @@
using Microsoft.AspNetCore.Diagnostics;
using Messenger.Api.Endpoints;
using Messenger.Api.Services;
using Messenger.Api.Data;
using Messenger.Api.Jobs;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication;
if (args is ["--render-attachment", var mime, var pixels, var pipeline])
return await ImageRenderer.RunAsync(mime, long.Parse(pixels), int.Parse(pipeline));
if (args is ["--failed-jobs"])
return await JobOperations.RunAsync(args[0]);
if (args is ["--replay-job" or "--upgrade-attachment", var identifier])
return Guid.TryParse(identifier, out var id) ? await JobOperations.RunAsync(args[0], id) : 2;
if (args is ["--worker"] or ["--dispatch"])
{
await QueueHost.RunAsync(publisher: args[0] == "--dispatch");
return 0;
}
// Режим для 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(sp => S3Settings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton(sp => UploadSettings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton<UploadGate>();
builder.Services.AddSingleton(sp => UploadCleanupSettings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton<UploadCleanup>();
builder.Services.AddHostedService<UploadCleanupWorker>();
builder.Services.AddSingleton<IAttachmentStorage>(sp =>
{
var s3Settings = sp.GetRequiredService<S3Settings>();
return new S3AttachmentStorage(s3Settings);
});
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;
}
if (args.Contains("--cleanup-uploads"))
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25));
var result = await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(timeout.Token);
Console.WriteLine(JsonSerializer.Serialize(result));
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: 413 } tooLarge)
return ApiErrors.Error(context, 413, "payload_too_large", "Файл превышает лимит размера").ExecuteAsync(context);
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) || error is Amazon.S3.AmazonS3Exception or HttpRequestException)
{
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"),
413 => ("payload_too_large", "Файл превышает лимит размера"),
503 => ("unavailable", "Сервис временно недоступен"),
_ => ("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 (сессии, данные, ключи
// идемпотентности), а загрузки требуют S3. Valkey не критичен: без него чтение идёт напрямую из PostgreSQL. После SIGTERM — всегда 503:
// балансировщик выводит экземпляр из ротации ещё до закрытия слушателя. Таймаут проверки (1 с) меньше таймаута
// проверки в HAProxy (2 с), чтобы зависшая БД давала явный 503, а не обрыв проверки.
app.MapGet("/health/ready", async (HttpContext context, MessengerDbContext db, ShutdownState shutdown, IAttachmentStorage storage) =>
{
if (shutdown.Draining)
{
return ApiErrors.Error(context, 503, "unavailable", "Экземпляр останавливается");
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(1));
try
{
await storage.CheckAsync(timeout.Token);
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", "Зависимость недоступна");
}
catch (Exception ex) when (ex is Amazon.S3.AmazonS3Exception or HttpRequestException)
{
return ApiErrors.Error(context, 503, "unavailable", "Хранилище недоступно");
}
});
app.MapUserEndpoints();
app.MapAuthEndpoints();
app.MapChatEndpoints();
app.MapMessageEndpoints();
app.MapAttachmentEndpoints();
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"
}
}
}
}
+37
View File
@@ -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);
}
+91
View File
@@ -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);
}
}
+56
View File
@@ -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;
}
}
}
+90
View File
@@ -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,21 @@
namespace Messenger.Api.Services;
public interface IAttachmentStorage
{
Task CheckAsync(CancellationToken ct);
Task PutAsync(
string objectKey,
Stream content,
string contentType,
CancellationToken ct,
bool createOnly = false);
Task CopyToAsync(
string objectKey,
Stream destination,
CancellationToken ct);
Task DeleteAsync(
string objectKey,
CancellationToken ct);
}
@@ -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,147 @@
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, Guid[]? attachmentIds = null) =>
// Пустой список сохраняет отпечаток старых текстовых запросов lab3.
SHA256.HashData(Encoding.UTF8.GetBytes($"message\n{text.Length}\n{text}" +
(attachmentIds is { Length: > 0 } ? "\nattachments\n" + string.Join(",", attachmentIds.Select(x => x.ToString("N"))) : "")));
// Атомарно «занимает» ключ в транзакции вызывающего. Ключевое свойство — 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,16 @@
namespace Messenger.Api.Services;
// Ограничивает память даже при неожиданном размере объекта в S3.
public sealed class LimitedDownloadStream(long maximum) : MemoryStream
{
private void Check(int count)
{
if (Position + count > maximum) throw new IOException("Object exceeds its metadata size");
}
public override void Write(byte[] buffer, int offset, int count) { Check(count); base.Write(buffer, offset, count); }
public override void Write(ReadOnlySpan<byte> buffer) { Check(buffer.Length); base.Write(buffer); }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct)
{ Check(count); return base.WriteAsync(buffer, offset, count, ct); }
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken ct = default)
{ Check(buffer.Length); return base.WriteAsync(buffer, ct); }
}
@@ -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,56 @@
using System.Buffers.Binary;
using System.IO.Compression;
namespace Messenger.Api.Services;
// Дополняет декодер: проверяет границы и CRC всех PNG chunks, включая IDAT.
public static class PngIntegrity
{
private static readonly uint[] Table = Enumerable.Range(0, 256).Select(i =>
{
uint c = (uint)i;
for (var bit = 0; bit < 8; bit++) c = (c & 1) != 0 ? 0xedb88320U ^ (c >> 1) : c >> 1;
return c;
}).ToArray();
public static async Task ValidateAsync(Stream stream, long maxDecodedBytes, CancellationToken ct)
{
stream.Position = 8;
var header = new byte[8];
var buffer = new byte[65536];
var checksum = new byte[4];
using var compressed = new MemoryStream(); // IDAT не больше уже ограниченного файла (10 MiB).
while (stream.Position < stream.Length)
{
await stream.ReadExactlyAsync(header, ct);
var length = BinaryPrimitives.ReadUInt32BigEndian(header);
if (length > stream.Length - stream.Position - 4) throw new InvalidDataException("Invalid PNG chunk");
uint crc = uint.MaxValue;
for (var i = 4; i < 8; i++) crc = Table[(crc ^ header[i]) & 255] ^ (crc >> 8);
long remaining = length;
while (remaining > 0)
{
var count = (int)Math.Min(buffer.Length, remaining);
await stream.ReadExactlyAsync(buffer.AsMemory(0, count), ct);
if (header.AsSpan(4, 4).SequenceEqual("IDAT"u8))
await compressed.WriteAsync(buffer.AsMemory(0, count), ct);
for (var i = 0; i < count; i++) crc = Table[(crc ^ buffer[i]) & 255] ^ (crc >> 8);
remaining -= count;
}
await stream.ReadExactlyAsync(checksum, ct);
if ((crc ^ uint.MaxValue) != BinaryPrimitives.ReadUInt32BigEndian(checksum))
throw new InvalidDataException("Invalid PNG checksum");
}
// stbi распаковывает PNG до проверки длины пикселей: сначала проверяем
// размер zlib-потока самостоятельно, не выделяя память под распаковку.
compressed.Position = 0;
using var zlib = new ZLibStream(compressed, CompressionMode.Decompress);
long decoded = 0;
int read;
while ((read = await zlib.ReadAsync(buffer, ct)) != 0)
{
decoded += read;
if (decoded > maxDecodedBytes) throw new InvalidDataException("PNG decompression exceeds dimensions");
}
}
}
@@ -0,0 +1,88 @@
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System.Net;
using System.Security.Cryptography;
namespace Messenger.Api.Services;
public sealed class S3AttachmentStorage : IAttachmentStorage, IDisposable
{
private readonly AmazonS3Client _client;
private readonly string _bucket;
public S3AttachmentStorage(S3Settings settings)
{
var config = new AmazonS3Config
{
ServiceURL = settings.Endpoint,
ForcePathStyle = true,
AuthenticationRegion = settings.Region,
Timeout = TimeSpan.FromSeconds(15),
MaxErrorRetry = 1
};
var credentials = new BasicAWSCredentials(settings.AccessKey, settings.SecretKey);
_client = new AmazonS3Client(credentials, config);
_bucket = settings.Bucket;
}
public async Task PutAsync(string objectKey, Stream content, string contentType, CancellationToken ct, bool createOnly = false)
{
var request = new PutObjectRequest
{
BucketName = _bucket,
Key = objectKey,
InputStream = content,
ContentType = contentType,
IfNoneMatch = createOnly ? "*" : null,
// Поток принадлежит вызывающему коду, а не SDK.
AutoCloseStream = false
};
try
{
await _client.PutObjectAsync(request, ct);
}
catch (AmazonS3Exception ex) when (createOnly && ex.StatusCode == HttpStatusCode.PreconditionFailed)
{
// Повтор после аварии использует уже записанные байты. Несовпадение закрывает публикацию.
using var existing = new LimitedDownloadStream(content.Length);
await CopyToAsync(objectKey, existing, ct);
content.Position = 0;
var expected = await SHA256.HashDataAsync(content, ct);
var actual = SHA256.HashData(existing.GetBuffer().AsSpan(0, (int)existing.Length));
if (existing.Length != content.Length || !expected.AsSpan().SequenceEqual(actual))
throw new IOException("Existing object differs from the pipeline result");
}
}
public async Task CopyToAsync(string objectKey, Stream destination, CancellationToken ct)
{
var request = new GetObjectRequest
{
BucketName = _bucket,
Key = objectKey
};
using var response = await _client.GetObjectAsync(request, ct);
await response.ResponseStream.CopyToAsync(destination, ct);
}
public async Task DeleteAsync(string objectKey, CancellationToken ct)
{
var request = new DeleteObjectRequest
{
BucketName = _bucket,
Key = objectKey
};
await _client.DeleteObjectAsync(request, ct);
}
public void Dispose() => _client.Dispose();
public async Task CheckAsync(CancellationToken ct) =>
await _client.GetBucketLocationAsync(new GetBucketLocationRequest { BucketName = _bucket }, ct);
}
@@ -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));
}
+166
View File
@@ -0,0 +1,166 @@
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 S3Settings(string Bucket, string Endpoint, string Region, string AccessKey, string SecretKey)
{
public static S3Settings From(IConfiguration configuration)
{
string Required(string name) => !string.IsNullOrWhiteSpace(configuration[name])
? configuration[name]!.Trim()
: throw new InvalidOperationException($"{name} не задан");
string ReadSecret(string name)
{
var value = File.ReadAllText(Required(name)).Trim();
return value.Length > 0 ? value
: throw new InvalidOperationException($"Файл {name} пуст");
}
var endpoint = Required("S3_ENDPOINT");
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
uri.Scheme is not ("http" or "https"))
{
throw new InvalidOperationException("S3_ENDPOINT должен быть HTTP/HTTPS URL");
}
return new S3Settings(Required("S3_BUCKET"), endpoint,
configuration["S3_REGION"]?.Trim() is { Length: > 0 } region ? region : "us-east-1",
ReadSecret("S3_ACCESS_KEY_ID_FILE"), ReadSecret("S3_SECRET_ACCESS_KEY_FILE"));
}
public override string ToString() => $"S3Settings {{ Bucket = {Bucket}, Endpoint = {Endpoint}, Region = {Region} }}";
}
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;
}
+13
View File
@@ -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);
}
}
+107
View File
@@ -0,0 +1,107 @@
using Messenger.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace Messenger.Api.Services;
public sealed record UploadCleanupSettings(TimeSpan Grace, TimeSpan Interval)
{
public static UploadCleanupSettings From(IConfiguration configuration)
{
var grace = configuration.GetValue("UPLOAD_CLEANUP_GRACE_SECONDS", 300);
var interval = configuration.GetValue("UPLOAD_CLEANUP_INTERVAL_SECONDS", 30);
// Grace > HTTP timeout 30 с + SDK retry/таймауты + запас на отмену.
if (grace < 120 || interval < 1)
throw new InvalidOperationException("Cleanup: grace >= 120, interval >= 1");
return new(TimeSpan.FromSeconds(grace), TimeSpan.FromSeconds(interval));
}
}
public sealed record UploadCleanupResult(int Scanned, int Deleted, int Protected, int Failed);
public sealed class UploadCleanup(IServiceScopeFactory scopes, UploadCleanupSettings settings, ILogger<UploadCleanup> logger)
{
public async Task<UploadCleanupResult> RunOnceAsync(CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
var storage = scope.ServiceProvider.GetRequiredService<IAttachmentStorage>();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(TimeSpan.FromSeconds(20));
ct = deadline.Token;
await using var tx = await db.Database.BeginTransactionAsync(ct);
// Несколько реплик не очищают одну запись одновременно. Финализация upload
// блокирует ту же строку и запрещена после истечения lease.
var intents = await db.UploadIntents.FromSqlRaw("""
SELECT * FROM upload_intents
WHERE expires_at <= clock_timestamp() AND next_attempt_at <= clock_timestamp()
ORDER BY next_attempt_at, id LIMIT 16 FOR UPDATE SKIP LOCKED
""").ToListAsync(ct);
int deleted = 0, protectedCount = 0, failed = 0;
foreach (var intent in intents)
{
if (await db.Attachments.AsNoTracking().AnyAsync(a => a.ObjectKey == intent.ObjectKey, ct))
{
db.UploadIntents.Remove(intent); // Опубликованный объект никогда не удаляем.
protectedCount++;
continue;
}
var staging = intent.ObjectKey == $"staging/{intent.Id:N}";
if (!staging && intent.ObjectKey != $"originals/{intent.Id:N}")
throw new InvalidOperationException("Invalid cleanup object key");
string? stageOwner = null;
if (staging)
{
stageOwner = await db.Attachments.Where(a => a.Id == intent.Id)
.Select(a => a.Status).SingleOrDefaultAsync(ct);
if (stageOwner is "queued" or "processing" &&
await db.AttachmentJobs.AnyAsync(j => j.AttachmentId == intent.Id && j.SourceKey == intent.ObjectKey &&
j.PipelineVersion == j.Attachment.PipelineVersion, ct))
{
db.UploadIntents.Remove(intent); // Активная job владеет staging до терминального перехода.
protectedCount++;
continue;
}
}
intent.NextAttemptAt = DateTimeOffset.UtcNow + settings.Interval;
try
{
await storage.DeleteAsync(intent.ObjectKey, ct); // DELETE отсутствующего объекта идемпотентен.
intent.DeleteCount++;
deleted++;
if (stageOwner is not null)
db.UploadIntents.Remove(intent);
// Tombstone сохраняется: даже запоздавший PUT после crash не
// превратится в забытый объект. Цена — запись в БД на неудачную загрузку.
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed++;
logger.LogWarning("S3 cleanup retry for {UploadId}: {Error}", intent.Id, ex.GetType().Name);
}
}
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
return new(intents.Count, deleted, protectedCount, failed);
}
}
public sealed class UploadCleanupWorker(UploadCleanup cleanup, UploadCleanupSettings settings,
ILogger<UploadCleanupWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(settings.Interval);
while (!stoppingToken.IsCancellationRequested)
{
try
{
var result = await cleanup.RunOnceAsync(stoppingToken);
if (result.Scanned > 0) logger.LogInformation("Upload cleanup: {Result}", result);
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{ logger.LogWarning("Upload cleanup will retry: {Error}", ex.GetType().Name); }
try { if (!await timer.WaitForNextTickAsync(stoppingToken)) break; }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
}
@@ -0,0 +1,20 @@
namespace Messenger.Api.Services;
public sealed record UploadSettings(long MaxBytes, long MaxPixels)
{
public static UploadSettings From(IConfiguration configuration)
{
var bytes = configuration.GetValue("MAX_UPLOAD_BYTES", 10485760L);
var pixels = configuration.GetValue("MAX_IMAGE_PIXELS", 40000000L);
if (bytes is < 1 or > 10485760 || pixels is < 1 or > 40000000)
throw new InvalidOperationException("Лимиты upload должны быть положительными и не превышать 10 MiB / 40 млн пикселей");
return new(bytes, pixels);
}
}
// Ограничиваем число одновременных декодирований на реплике (до 160 MB пикселей).
public sealed class UploadGate : IDisposable
{
public SemaphoreSlim Slots { get; } = new(1);
public void Dispose() => Slots.Dispose();
}
@@ -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"
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}