forked from mtusi2026/mtusi2026lab3
Миграции балансировка запросов идемпотентность graceful shutdown readines
This commit is contained in:
@@ -7,6 +7,7 @@ COPY build.gradle.* settings.gradle* build.gradle.kts* settings.gradle.kts* ./
|
|||||||
RUN dos2unix gradlew && chmod +x gradlew
|
RUN dos2unix gradlew && chmod +x gradlew
|
||||||
RUN ./gradlew dependencies --no-daemon || true
|
RUN ./gradlew dependencies --no-daemon || true
|
||||||
COPY src src
|
COPY src src
|
||||||
|
RUN apk add --no-cache curl
|
||||||
RUN ./gradlew bootJar -x test --no-daemon
|
RUN ./gradlew bootJar -x test --no-daemon
|
||||||
|
|
||||||
FROM eclipse-temurin:22-jre-alpine AS runtime
|
FROM eclipse-temurin:22-jre-alpine AS runtime
|
||||||
|
|||||||
@@ -54,6 +54,12 @@ services:
|
|||||||
SERVER_SHUTDOWN: graceful
|
SERVER_SHUTDOWN: graceful
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 3
|
replicas: 3
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "wget -q -O- http://127.0.0.1:8080/health/live || exit 1"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
start_period: 40s
|
||||||
|
|
||||||
nginx:
|
nginx:
|
||||||
image: nginx:1.27-alpine
|
image: nginx:1.27-alpine
|
||||||
|
|||||||
@@ -6,14 +6,19 @@ events {
|
|||||||
|
|
||||||
http {
|
http {
|
||||||
upstream api_backend {
|
upstream api_backend {
|
||||||
# Имя сервиса Compose DNS: все задачи api
|
least_conn;
|
||||||
server api:8080;
|
server api:8080 max_fails=2 fail_timeout=5s;
|
||||||
# sticky НЕ использовать
|
|
||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
|
|
||||||
|
location /health/live {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_connect_timeout 1s;
|
||||||
|
proxy_read_timeout 2s;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://api_backend;
|
proxy_pass http://api_backend;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|||||||
@@ -1,4 +1,25 @@
|
|||||||
package org.example.config;
|
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 {
|
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 {
|
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)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public Message sendMessage(
|
public Message sendMessage(
|
||||||
@PathVariable("id") UUID id,
|
@PathVariable("id") UUID id,
|
||||||
|
@RequestHeader("Idempotency-Key") String idempotencyKey,
|
||||||
@Valid @RequestBody CreateMessageDto messageDto
|
@Valid @RequestBody CreateMessageDto messageDto
|
||||||
) {
|
) {
|
||||||
UUID senderId = userService.getCurrentUser().getId();
|
UUID senderId = userService.getCurrentUser().getId();
|
||||||
return messageService.sendMessage(id, senderId, messageDto);
|
return messageService.sendMessage(id, senderId, messageDto, idempotencyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}/messages")
|
@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.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.sql.Connection;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/health")
|
@RequestMapping("/health")
|
||||||
public class HealthController {
|
public class HealthController {
|
||||||
|
|
||||||
@GetMapping({"", "/live", "/ready"})
|
private final DataSource dataSource;
|
||||||
public ResponseEntity<Map<String, String>> health() {
|
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"));
|
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.ResponseEntity;
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
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.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||||
@@ -72,6 +73,21 @@ public class GlobalExceptionHandler {
|
|||||||
.body(body);
|
.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)
|
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||||
public ResponseEntity<ErrorResponse> handleMalformedJson(
|
public ResponseEntity<ErrorResponse> handleMalformedJson(
|
||||||
HttpMessageNotReadableException ex,
|
HttpMessageNotReadableException ex,
|
||||||
|
|||||||
@@ -1,4 +1,43 @@
|
|||||||
package org.example.model;
|
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 {
|
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;
|
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.dto.update.UpdateMessageDto;
|
||||||
import org.example.exception.ForbiddenException;
|
import org.example.exception.ForbiddenException;
|
||||||
import org.example.exception.NotFoundException;
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.model.IdempotencyKey;
|
||||||
import org.example.model.Message;
|
import org.example.model.Message;
|
||||||
|
import org.example.repository.IdempotencyKeyRepository;
|
||||||
import org.example.repository.MessageRepository;
|
import org.example.repository.MessageRepository;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -15,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -22,23 +26,54 @@ import java.util.UUID;
|
|||||||
public class MessageService {
|
public class MessageService {
|
||||||
|
|
||||||
private final MessageRepository messageRepository;
|
private final MessageRepository messageRepository;
|
||||||
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||||
private final ChatService chatService;
|
private final ChatService chatService;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Message sendMessage(UUID chatId, UUID senderId, CreateMessageDto messageObject) {
|
public Message sendMessage(
|
||||||
|
UUID chatId,
|
||||||
|
UUID senderId,
|
||||||
|
CreateMessageDto messageObject,
|
||||||
|
String idempotencyKey){
|
||||||
chatService.requireMember(chatId);
|
chatService.requireMember(chatId);
|
||||||
if (!chatService.isMember(chatId, senderId)){
|
if (!chatService.isMember(chatId, senderId)){
|
||||||
throw new ForbiddenException("Пользователь не является участником чата");
|
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()
|
Message message = Message.builder()
|
||||||
.chatId(chatId)
|
.chatId(chatId)
|
||||||
.senderId(senderId)
|
.senderId(senderId)
|
||||||
.text(messageObject.getText())
|
.text(messageObject.getText())
|
||||||
.createdAt(Instant.now())
|
.createdAt(Instant.now())
|
||||||
.build();
|
.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ spring:
|
|||||||
deserialization:
|
deserialization:
|
||||||
fail-on-unknown-properties: true
|
fail-on-unknown-properties: true
|
||||||
lifecycle:
|
lifecycle:
|
||||||
timeout-per-shutdown-cycle=10s:
|
timeout-per-shutdown-phase: 20s
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
datasource:
|
datasource:
|
||||||
@@ -59,7 +59,7 @@ logging:
|
|||||||
:servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver: DEBUG
|
:servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver: DEBUG
|
||||||
|
|
||||||
server:
|
server:
|
||||||
shutdown=graceful:
|
shutdown: graceful
|
||||||
|
|
||||||
management:
|
management:
|
||||||
endpoints:
|
endpoints:
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
CREATE TABLE idempotency_keys (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_idempotency_user_chat_key
|
||||||
|
UNIQUE (user_id, chat_id, idempotency_key)
|
||||||
|
);
|
||||||
Reference in New Issue
Block a user