ЛР 3: масштабирование и отказоустойчивость API
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.github.f4b6a3.uuid.UuidCreator;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.IdempotentMessage;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.example.mtusi_messenger.dto.CreateMessageRequest;
|
||||
import com.example.mtusi_messenger.model.Message;
|
||||
import com.example.mtusi_messenger.repository.MessageRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class MessageService {
|
||||
private static final String METHOD = "POST";
|
||||
private final MessageRepository messages;
|
||||
private final ChatService chats;
|
||||
private final CursorService cursors;
|
||||
private final Duration idempotencyTtl;
|
||||
|
||||
public MessageService(
|
||||
MessageRepository messages,
|
||||
ChatService chats,
|
||||
CursorService cursors,
|
||||
@Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds
|
||||
) {
|
||||
if (idempotencyTtlSeconds < 86400) {
|
||||
throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours");
|
||||
}
|
||||
this.messages = messages;
|
||||
this.chats = chats;
|
||||
this.cursors = cursors;
|
||||
this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) {
|
||||
chats.getAccessible(chatId, senderId);
|
||||
String path = "/api/v1/chats/" + chatId + "/messages";
|
||||
byte[] requestHash = hash(r.text());
|
||||
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
|
||||
|
||||
// The transaction-scoped PostgreSQL advisory lock serializes the same
|
||||
// idempotency scope across every API replica. A hash collision only
|
||||
// causes harmless extra serialization; the full scope is still checked.
|
||||
messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey);
|
||||
messages.deleteExpiredIdempotency(
|
||||
senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl));
|
||||
|
||||
var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey);
|
||||
if (existing.isPresent()) {
|
||||
IdempotentMessage value = existing.get();
|
||||
if (!Arrays.equals(value.requestHash(), requestHash)) {
|
||||
throw ApiExceptions.conflict("Idempotency-Key was already used with another request body");
|
||||
}
|
||||
return value.message();
|
||||
}
|
||||
|
||||
Message message = messages.save(new Message(
|
||||
UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now));
|
||||
messages.saveIdempotency(
|
||||
senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now);
|
||||
return message;
|
||||
}
|
||||
|
||||
private static byte[] hash(String text) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return digest.digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is unavailable", e);
|
||||
}
|
||||
}
|
||||
public List<Message> page(UUID chatId, UUID userId, int limit, String cursor) {
|
||||
chats.getAccessible(chatId, userId);
|
||||
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId);
|
||||
return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1);
|
||||
}
|
||||
public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; }
|
||||
}
|
||||
Reference in New Issue
Block a user