forked from mtusi2026/mtusi2026lab3
Миграции балансировка запросов идемпотентность graceful shutdown readines
This commit is contained in:
@@ -1,4 +1,25 @@
|
||||
package org.example.config;
|
||||
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class GracefulShutdownListener {
|
||||
|
||||
private final ReadinessState state;
|
||||
|
||||
public GracefulShutdownListener(ReadinessState state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
public void onClose(){
|
||||
state.setReady(false);
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
package org.example.model;
|
||||
package org.example.config;
|
||||
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Component
|
||||
public class ReadinessState {
|
||||
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||
public boolean isReady() {
|
||||
return ready.get();
|
||||
}
|
||||
public void setReady(boolean v) {
|
||||
ready.set(v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,10 +73,11 @@ public class ChatController {
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Message sendMessage(
|
||||
@PathVariable("id") UUID id,
|
||||
@RequestHeader("Idempotency-Key") String idempotencyKey,
|
||||
@Valid @RequestBody CreateMessageDto messageDto
|
||||
) {
|
||||
UUID senderId = userService.getCurrentUser().getId();
|
||||
return messageService.sendMessage(id, senderId, messageDto);
|
||||
return messageService.sendMessage(id, senderId, messageDto, idempotencyKey);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/messages")
|
||||
|
||||
@@ -5,15 +5,44 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/health")
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping({"", "/live", "/ready"})
|
||||
public ResponseEntity<Map<String, String>> health() {
|
||||
private final DataSource dataSource;
|
||||
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||
|
||||
public HealthController(DataSource dataSource) {
|
||||
this.dataSource = dataSource;
|
||||
}
|
||||
|
||||
@GetMapping({"/live"})
|
||||
public ResponseEntity<Map<String, String>> live() {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
|
||||
@GetMapping("/ready")
|
||||
public ResponseEntity<Map<String, String>> ready(){
|
||||
if (!ready.get()){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "NOT_READY"));
|
||||
}
|
||||
try (Connection c = dataSource.getConnection()){
|
||||
if (!c.isValid(1)){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||
}
|
||||
} catch (Exception e){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("Status", "UP"));
|
||||
}
|
||||
|
||||
public void markNotReady() {
|
||||
ready.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
@@ -72,6 +73,21 @@ public class GlobalExceptionHandler {
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMissingHeader(
|
||||
MissingRequestHeaderException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("bad_request", "Malformed JSON request body", reqId)
|
||||
);
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMalformedJson(
|
||||
HttpMessageNotReadableException ex,
|
||||
|
||||
@@ -1,4 +1,43 @@
|
||||
package org.example.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "idempotency_keys",
|
||||
uniqueConstraints = @UniqueConstraint(
|
||||
name = "uq_idempotency_user_chat_key",
|
||||
columnNames = {"user_id", "chat_id", "idempotency_key"}))
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class IdempotencyKey {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "idempotency_key", nullable = false)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Column(name = "message_id", nullable = false)
|
||||
private UUID messageId;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
package org.example.repository;
|
||||
|
||||
public interface IdempotecyKeyRepository {
|
||||
import org.example.model.IdempotencyKey;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IdempotencyKeyRepository extends JpaRepository<IdempotencyKey, UUID> {
|
||||
Optional<IdempotencyKey> findByUserIdAndChatIdAndIdempotencyKey(
|
||||
UUID userId,
|
||||
UUID chatId,
|
||||
String idempotencyKey
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import org.example.dto.create.CreateMessageDto;
|
||||
import org.example.dto.update.UpdateMessageDto;
|
||||
import org.example.exception.ForbiddenException;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.model.IdempotencyKey;
|
||||
import org.example.model.Message;
|
||||
import org.example.repository.IdempotencyKeyRepository;
|
||||
import org.example.repository.MessageRepository;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -15,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@@ -22,23 +26,54 @@ import java.util.UUID;
|
||||
public class MessageService {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||
private final ChatService chatService;
|
||||
|
||||
@Transactional
|
||||
public Message sendMessage(UUID chatId, UUID senderId, CreateMessageDto messageObject) {
|
||||
public Message sendMessage(
|
||||
UUID chatId,
|
||||
UUID senderId,
|
||||
CreateMessageDto messageObject,
|
||||
String idempotencyKey){
|
||||
chatService.requireMember(chatId);
|
||||
if (!chatService.isMember(chatId, senderId)){
|
||||
throw new ForbiddenException("Пользователь не является участником чата");
|
||||
}
|
||||
|
||||
String key = idempotencyKey.trim();
|
||||
|
||||
Optional<IdempotencyKey> exists = idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
||||
|
||||
if (exists.isPresent()){
|
||||
return messageRepository.findById(exists.get().getMessageId())
|
||||
.orElseThrow(() -> new IllegalArgumentException("Сообщения нет"));
|
||||
}
|
||||
|
||||
Message message = Message.builder()
|
||||
.chatId(chatId)
|
||||
.senderId(senderId)
|
||||
.text(messageObject.getText())
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
message = messageRepository.save(message);
|
||||
|
||||
return messageRepository.save(message);
|
||||
try {
|
||||
idempotencyKeyRepository.saveAndFlush(
|
||||
IdempotencyKey.builder()
|
||||
.userId(senderId)
|
||||
.chatId(chatId)
|
||||
.idempotencyKey(key)
|
||||
.messageId(message.getId())
|
||||
.build()
|
||||
);
|
||||
} catch (DataIntegrityViolationException e){
|
||||
IdempotencyKey rec = idempotencyKeyRepository
|
||||
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
||||
.orElseThrow(() -> e);
|
||||
return messageRepository.findById(rec.getUserId())
|
||||
.orElseThrow(()-> e);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user