ЛР 3: масштабирование и отказоустойчивость API
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.cache.UserCache;
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final UserRepository users;
|
||||
private final SessionRepository sessions;
|
||||
private final UserCache userCache;
|
||||
private final long ttlSeconds;
|
||||
|
||||
public AuthenticationService(
|
||||
UserRepository users,
|
||||
SessionRepository sessions,
|
||||
UserCache userCache,
|
||||
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
||||
) {
|
||||
if (ttlSeconds <= 0) {
|
||||
throw new IllegalArgumentException("Session TTL must be positive");
|
||||
}
|
||||
this.users = users;
|
||||
this.sessions = sessions;
|
||||
this.userCache = userCache;
|
||||
this.ttlSeconds = ttlSeconds;
|
||||
}
|
||||
|
||||
public IssuedSession issueSession(User user) {
|
||||
String token = newToken();
|
||||
Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
|
||||
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
|
||||
sessions.save(new Session(
|
||||
UUID.randomUUID(),
|
||||
user.id(),
|
||||
hashToken(token),
|
||||
createdAt,
|
||||
expiresAt));
|
||||
return new IssuedSession(token, expiresAt, user);
|
||||
}
|
||||
|
||||
public SessionPrincipal authenticateBearer(String token) {
|
||||
byte[] tokenHash = hashToken(token);
|
||||
try {
|
||||
UUID userId = sessions.findActiveUserId(tokenHash)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
User user = userCache.find(userId).orElseGet(() -> {
|
||||
User loaded = users.findById(userId)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
userCache.put(loaded);
|
||||
return loaded;
|
||||
});
|
||||
return new SessionPrincipal(user, tokenHash);
|
||||
} catch (DataAccessException e) {
|
||||
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void revoke(SessionPrincipal principal) {
|
||||
try {
|
||||
if (!sessions.revoke(principal.tokenHash())) {
|
||||
throw new BadCredentialsException("Invalid or expired session");
|
||||
}
|
||||
} catch (DataAccessException e) {
|
||||
throw new AuthenticationServiceException("Authentication database is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private byte[] hashToken(String token) {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256")
|
||||
.digest(token.getBytes(StandardCharsets.US_ASCII));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
public record IssuedSession(String token, Instant expiresAt, User user) {}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.mtusi_messenger.dto.CreateChatRequest;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.Chat;
|
||||
import com.example.mtusi_messenger.repository.ChatRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
|
||||
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
|
||||
public Chat create(CreateChatRequest r, UUID caller) {
|
||||
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
|
||||
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
|
||||
return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids),
|
||||
Instant.now().truncatedTo(ChronoUnit.MICROS)));
|
||||
}
|
||||
public Chat getAccessible(UUID chatId, UUID userId) {
|
||||
users.get(userId);
|
||||
if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found");
|
||||
return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found"));
|
||||
}
|
||||
public List<Chat> page(UUID userId, int limit, String cursor) {
|
||||
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId);
|
||||
return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1);
|
||||
}
|
||||
public String nextCursor(UUID userId,
|
||||
Chat last,
|
||||
boolean hasNext
|
||||
) {
|
||||
return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class CursorService {
|
||||
private final ObjectMapper mapper;
|
||||
public CursorService(ObjectMapper mapper) { this.mapper = mapper; }
|
||||
|
||||
public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) {
|
||||
try {
|
||||
byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(json);
|
||||
} catch (Exception e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
public Cursor decode(String raw, String resource, UUID resourceId) {
|
||||
if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
||||
try {
|
||||
CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class);
|
||||
if (p.v != 1
|
||||
|| !resource.equals(p.resource)
|
||||
|| !Objects.equals(resourceId, p.resourceId)
|
||||
|| p.createdAt() == null
|
||||
|| p.createdAt().isBlank()
|
||||
|| p.id() == null
|
||||
) throw ApiExceptions.invalid("Invalid cursor");
|
||||
return new Cursor(Instant.parse(p.createdAt), p.id);
|
||||
} catch (ApiException e) { throw e; }
|
||||
catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); }
|
||||
}
|
||||
public record Cursor(Instant createdAt, UUID id) {}
|
||||
private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {}
|
||||
private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import com.example.mtusi_messenger.dto.CreateUserRequest;
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
private final UserRepository users;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public User create(CreateUserRequest r) {
|
||||
String username = r.username(); String display = r.display_name();
|
||||
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
|
||||
String passwordHash = passwordEncoder.encode(r.password());
|
||||
try {
|
||||
return users.save(new User(UUID.randomUUID(), username, display,
|
||||
Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash);
|
||||
} catch (DuplicateKeyException e) {
|
||||
throw ApiExceptions.conflict("Username is already taken");
|
||||
}
|
||||
}
|
||||
public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); }
|
||||
public boolean exists(UUID id) { return users.findById(id).isPresent(); }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class UuidValidator {
|
||||
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile(
|
||||
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
);
|
||||
|
||||
private UuidValidator() {}
|
||||
|
||||
public static UUID parse(String value) {
|
||||
if (value == null || !UUID_PATTERN.matcher(value).matches()) {
|
||||
throw ApiExceptions.invalid("Invalid UUID");
|
||||
}
|
||||
|
||||
try {
|
||||
return UUID.fromString(value);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiExceptions.invalid("Invalid UUID");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user