complete level 5 track 1

This commit is contained in:
2026-10-15 13:04:16 +03:00
parent 9d0080db10
commit 4918969c6b
40 changed files with 877 additions and 53 deletions
@@ -0,0 +1,10 @@
package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app.idempotency")
public record IdempotencyProperties(
int keyMaxLength,
String keyPattern,
int retentionHours
) {}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app.instance")
public record InstanceProperties(String id) {
}
@@ -5,6 +5,7 @@
*/
package ru.mtusi.messenger.controller;
import jakarta.servlet.http.HttpServletRequest;
import ru.mtusi.messenger.dto.SessionDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
@@ -69,7 +70,7 @@ public interface AuthApi {
)
ResponseEntity<SessionDTO> createSession(
HttpServletRequest request
);
@@ -13,10 +13,9 @@ import ru.mtusi.messenger.service.AuthService;
@RequiredArgsConstructor
public class AuthController implements AuthApi {
private final AuthService authService;
private final HttpServletRequest request;
@Override
public ResponseEntity<SessionDTO> createSession() {
public ResponseEntity<SessionDTO> createSession(HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION)));
}
@@ -9,7 +9,6 @@ import ru.mtusi.messenger.service.HealthService;
@RestController
@RequiredArgsConstructor
public class HealthController implements HealthApi {
private final HealthService healthService;
@Override
@@ -19,8 +19,8 @@ public class MessageController implements MessagesApi {
private final MessageService messageService;
@Override
public ResponseEntity<MessageDTO> createMessage(UUID chatId, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO));
public ResponseEntity<MessageDTO> createMessage(UUID chatId, String idempotencyKey, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO, idempotencyKey));
}
@Override
@@ -78,6 +78,8 @@ public interface MessagesApi {
ResponseEntity<MessageDTO> createMessage(
@Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH)
@PathVariable("chat_id") UUID chatId,
@Parameter(name = "Idempotency-Key", required = true, in = ParameterIn.HEADER)
@RequestHeader(value = "Idempotency-Key", required = true) String idempotencyKey,
@Parameter(name = "CreateMessageDTO", description = "", required = true)
@Valid @RequestBody CreateMessageDTO createMessageDTO,
@AuthenticationPrincipal SessionPrincipal principal
@@ -12,6 +12,7 @@ import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -138,6 +139,12 @@ public class GlobalExceptionHandler {
"Database error", req);
}
@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<ErrorDTO> missingHeader(MissingRequestHeaderException e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
"Missing header: " + e.getHeaderName(), req);
}
private ResponseEntity<ErrorDTO> respond(HttpStatus status,
ErrorErrorDTO.CodeEnum code,
String message,
@@ -0,0 +1,30 @@
package ru.mtusi.messenger.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import ru.mtusi.messenger.config.properties.InstanceProperties;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class InstanceIdFilter extends OncePerRequestFilter {
private final InstanceProperties props;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
response.setHeader("X-Instance-Id", props.id());
chain.doFilter(request, response);
}
}
@@ -5,6 +5,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@@ -13,17 +14,14 @@ import java.io.IOException;
import java.util.UUID;
@Component
@Order(1)
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class RequestIdFilter extends OncePerRequestFilter {
public static final String INSTANCE_ID = UUID.randomUUID().toString();
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String rid = UUID.randomUUID().toString();
res.setHeader("X-Request-Id", rid);
res.setHeader("X-Instance-Id", INSTANCE_ID);
req.setAttribute("requestId", rid);
MDC.put("requestId", rid);
try {
@@ -0,0 +1,47 @@
package ru.mtusi.messenger.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.time.Instant;
import java.util.UUID;
@Entity
@Table(name = "idempotency_keys")
@Getter
@Setter
public class IdempotencyKey {
@Id
@Column(nullable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(name = "user_id", nullable = false)
private UUID userId;
@Column(nullable = false, length = 16)
private String method;
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "idempotency_key", nullable = false, length = 128)
private String idempotencyKey;
@Column(name = "request_hash", nullable = false, length = 64)
private String requestHash;
@Column(name = "status_code")
private Short statusCode;
@JdbcTypeCode(SqlTypes.JSON)
@Column(name = "response_body", columnDefinition = "jsonb")
private String responseBody;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
}
@@ -0,0 +1,39 @@
package ru.mtusi.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import ru.mtusi.messenger.model.IdempotencyKey;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface IdempotencyRepository extends JpaRepository<IdempotencyKey, UUID> {
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = """
INSERT INTO idempotency_keys
(user_id, method, chat_id, idempotency_key, request_hash, created_at)
VALUES (:userId, :method, :chatId, :key, :hash, NOW())
ON CONFLICT (user_id, method, chat_id, idempotency_key) DO NOTHING
""", nativeQuery = true)
int tryClaim(UUID userId, String method, UUID chatId, String key, String hash);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = """
UPDATE idempotency_keys
SET status_code = :statusCode,
response_body = CAST(:body AS jsonb)
WHERE user_id = :userId
AND method = :method
AND chat_id = :chatId
AND idempotency_key = :key
""", nativeQuery = true)
int commitResponse(UUID userId, String method, UUID chatId, String key,
int statusCode, String body);
Optional<IdempotencyKey> findByUserIdAndMethodAndChatIdAndIdempotencyKey(
UUID userId, String method, UUID chatId, String idempotencyKey);
}
@@ -0,0 +1,63 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.model.IdempotencyKey;
import ru.mtusi.messenger.repository.IdempotencyRepository;
import ru.mtusi.messenger.util.converter.IdempotencyPayloadConverter;
import ru.mtusi.messenger.validation.IdempotencyValidator;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.UUID;
import java.util.function.Supplier;
@Service
@RequiredArgsConstructor
public class IdempotencyService {
private final IdempotencyRepository idempotencyRepository;
private final IdempotencyPayloadConverter converter;
private final IdempotencyValidator validator;
@Transactional
public <T> T execute(UUID userId, String method, UUID chatId, String key,
Object requestBody, Class<T> responseType, Supplier<T> action) {
validator.validateKey(key);
String hash = hashRequest(requestBody);
int claimed = idempotencyRepository.tryClaim(userId, method, chatId, key, hash);
if (claimed == 0) {
return replay(userId, method, chatId, key, hash, responseType);
}
T result = action.get();
idempotencyRepository.commitResponse(userId, method, chatId, key, 201, converter.toJson(result));
return result;
}
private <T> T replay(UUID userId, String method, UUID chatId, String key,
String hash, Class<T> responseType) {
IdempotencyKey stored = idempotencyRepository
.findByUserIdAndMethodAndChatIdAndIdempotencyKey(userId, method, chatId, key)
.orElseThrow(() -> new IllegalStateException("Idempotency row not visible after conflict"));
if (!stored.getRequestHash().equals(hash))
throw new ConflictException("Idempotency-Key reused with a different request body");
if (stored.getStatusCode() == null || stored.getStatusCode() != 201)
throw new ConflictException("Idempotency-Key has unexpected status");
return converter.fromJson(stored.getResponseBody(), responseType);
}
private String hashRequest(Object body) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(converter.toJson(body).getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (Exception e) {
throw new IllegalStateException("Cannot hash request body", e);
}
}
}
@@ -13,13 +13,13 @@ import ru.mtusi.messenger.dto.MessagePageDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.exception.PayloadTooLargeException;
import ru.mtusi.messenger.mapper.ChatMapper;
import ru.mtusi.messenger.mapper.MessageMapper;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.Message;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.MessageRepository;
import ru.mtusi.messenger.util.CursorCodec;
import ru.mtusi.messenger.service.IdempotencyService;
import java.util.List;
import java.util.UUID;
@@ -28,7 +28,7 @@ import java.util.UUID;
@Slf4j
@RequiredArgsConstructor
public class MessageService {
private final ChatMapper chatMapper;
private final IdempotencyService idempotencyService;
private final MessageRepository messageRepository;
private final ChatService chatService;
private final UserService userService;
@@ -36,17 +36,22 @@ public class MessageService {
private final AppProperties appProperties;
@Transactional
public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO createMessageDTO) {
Chat chat = chatService.getChat(senderId, chatId);;
validateCreate(chatId, createMessageDTO);
public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO dto, String idempotencyKey) {
Chat chat = chatService.getChat(senderId, chatId);
return idempotencyService.execute(senderId, "POST", chatId, idempotencyKey, dto, MessageDTO.class,
() -> doCreate(senderId, chatId, dto, chat));
}
private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) {
validateCreate(chatId, dto);
User sender = userService.getReferenceUserById(senderId);
Message message = buildMessage(createMessageDTO, sender, chat);
Message message = buildMessage(dto, sender, chat);
try {
message = messageRepository.saveAndFlush(message);
} catch (DataIntegrityViolationException e) {
throw new NotFoundException("Cannot create message: referenced entity is missing");
}
log.info("Created message id={} in chat={}", message.getId(), chatId);
return messageMapper.toMessageDTO(message);
}
@@ -0,0 +1,29 @@
package ru.mtusi.messenger.util.converter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
@Component
@RequiredArgsConstructor
public class IdempotencyPayloadConverter {
private final JsonMapper jsonMapper;
public String toJson(Object payload) {
try {
return jsonMapper.writeValueAsString(payload);
} catch (JacksonException e) { // Исключение теперь непроверяемое
throw new IllegalStateException("Cannot serialize idempotency payload", e);
}
}
public <T> T fromJson(String json, Class<T> type) {
try {
return jsonMapper.readValue(json, type);
} catch (JacksonException e) {
throw new IllegalStateException("Corrupt idempotency payload", e);
}
}
}
@@ -0,0 +1,39 @@
package ru.mtusi.messenger.validation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.mtusi.messenger.config.properties.IdempotencyProperties;
import ru.mtusi.messenger.exception.InvalidRequestException;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
public class IdempotencyValidator {
private final IdempotencyProperties properties;
public void validateKey(String key) {
requireNotBlank(key);
requireMaxLength(key);
requirePattern(key);
}
private void requireNotBlank(String key) {
if (key == null || key.isEmpty()) {
throw new InvalidRequestException("Idempotency-Key header is required");
}
}
private void requireMaxLength(String key) {
if (key.length() > properties.keyMaxLength()) {
throw new InvalidRequestException("Idempotency-Key is too long");
}
}
private void requirePattern(String key) {
if (!Pattern.matches(properties.keyPattern(), key)) {
throw new InvalidRequestException("Idempotency-Key contains invalid characters");
}
}
}