262 lines
12 KiB
C#
262 lines
12 KiB
C#
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")));
|
||
}
|
||
}
|
||
}
|