package ru.mtuci.messenger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import ru.mtuci.messenger.repository.MessageRepository; import ru.mtuci.messenger.support.ApiClient; import ru.mtuci.messenger.support.LabContainers; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class IdempotencyIntegrationTest { @LocalServerPort int port; @Autowired JsonMapper jsonMapper; @Autowired MessageRepository messages; private ApiClient api; @DynamicPropertySource static void containers(DynamicPropertyRegistry registry) { LabContainers.register(registry); } @BeforeEach void client() { api = new ApiClient(port, jsonMapper); } @Test void replayConflictAndRejectedKey() { String password = "Example-only-not-a-real-secret-123"; JsonNode alice = register(name("ia"), password); String token = login(alice.get("username").asString(), password); String chatId = chat(token, List.of(alice.get("id").asString())); String key = "same-" + UUID.randomUUID(); ApiClient.Result rejected = send(token, chatId, "ещё не записано", key.replace("same", "bad key")); assertEquals(400, rejected.status()); assertFalse(rejected.instanceId().isBlank()); assertEquals(400, api.post("/api/v1/chats/" + chatId + "/messages", token, Map.of("text", "без ключа")).status()); String recover = "recover-" + UUID.randomUUID(); assertEquals(400, send(token, chatId, "", recover).status()); ApiClient.Result first = send(token, chatId, "Привет, мир", recover); assertEquals(201, first.status()); ApiClient.Result replay = send(token, chatId, "Привет, мир", recover); assertEquals(201, replay.status()); assertEquals(first.body(), replay.body()); assertEquals(409, send(token, chatId, "другой body", recover).status()); assertEquals(1, messages.countByChatId(UUID.fromString(chatId))); ApiClient.Result fresh = send(token, chatId, "Привет, мир", key); assertEquals(201, fresh.status()); assertNotEquals(first.body().get("id").asString(), fresh.body().get("id").asString()); } @Test void sameKeyIsIndependentAcrossUsersAndChats() { String password = "Example-only-not-a-real-secret-123"; JsonNode alice = register(name("ib"), password); JsonNode bob = register(name("ic"), password); String aliceToken = login(alice.get("username").asString(), password); String bobToken = login(bob.get("username").asString(), password); String shared = chat(aliceToken, List.of(alice.get("id").asString(), bob.get("id").asString())); String other = chat(aliceToken, List.of(alice.get("id").asString())); String key = "shared-" + UUID.randomUUID(); ApiClient.Result aliceMessage = send(aliceToken, shared, "общий ключ", key); ApiClient.Result bobMessage = send(bobToken, shared, "общий ключ", key); ApiClient.Result otherChat = send(aliceToken, other, "общий ключ", key); assertEquals(201, aliceMessage.status()); assertEquals(201, bobMessage.status()); assertEquals(201, otherChat.status()); assertNotEquals(aliceMessage.body().get("id").asString(), bobMessage.body().get("id").asString()); assertNotEquals(aliceMessage.body().get("id").asString(), otherChat.body().get("id").asString()); } @Test void parallelSameKeyCreatesOneMessage() throws Exception { String password = "Example-only-not-a-real-secret-123"; JsonNode alice = register(name("ip"), password); String token = login(alice.get("username").asString(), password); String chatId = chat(token, List.of(alice.get("id").asString())); String key = "parallel-" + UUID.randomUUID(); int threads = 8; ExecutorService pool = Executors.newFixedThreadPool(threads); CountDownLatch start = new CountDownLatch(1); try { List> futures = new ArrayList<>(); for (int i = 0; i < threads; i++) { futures.add(pool.submit(() -> { start.await(); return send(token, chatId, "одно сообщение", key); })); } start.countDown(); JsonNode body = null; for (Future future : futures) { ApiClient.Result result = future.get(); assertEquals(201, result.status()); if (body == null) { body = result.body(); } else { assertEquals(body, result.body()); } } } finally { pool.shutdownNow(); } assertEquals(1, messages.countByChatId(UUID.fromString(chatId))); } private ApiClient.Result send(String token, String chatId, String text, String key) { return api.post("/api/v1/chats/" + chatId + "/messages", token, Map.of("text", text), Map.of("Idempotency-Key", key)); } private String chat(String token, List members) { return api.post("/api/v1/chats", token, Map.of("title", "Идемпотентность", "member_ids", members)) .body().get("id").asString(); } private JsonNode register(String username, String password) { ApiClient.Result result = api.post("/api/v1/users", api.user(username, "Алиса", password)); assertEquals(201, result.status()); return result.body(); } private String login(String username, String password) { String basic = Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); ApiClient.Result session = api.postBasic("/api/v1/auth/sessions", basic); assertEquals(201, session.status()); return session.body().get("token").asString(); } private static String name(String prefix) { return (prefix + UUID.randomUUID().toString().replace("-", "")).substring(0, 20); } }