на 3 готво тесты валидны

This commit is contained in:
Dmitry
2026-10-29 22:46:26 +03:00
parent 36cbd70d37
commit 9b665ebb0f
12 changed files with 145 additions and 15 deletions
+1
View File
@@ -61,6 +61,7 @@ services:
retries: 3
start_period: 40s
nginx:
image: nginx:1.27-alpine
ports:
+18 -2
View File
@@ -15,8 +15,24 @@ http {
location /health/live {
proxy_pass http://api_backend;
proxy_connect_timeout 1s;
proxy_read_timeout 2s;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
proxy_next_upstream error timeout http_502 http_503 http_504;
}
location /health/ready {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
proxy_next_upstream error timeout http_502 http_503 http_504;
}
location / {
@@ -19,7 +19,13 @@ import java.io.IOException;
public class AuthFilter extends OncePerRequestFilter {
private final AuthService authService;
private final SessionRepository sessionRepository;
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
return path.startsWith("/health/")
|| path.startsWith("/actuator/");
}
@Override
protected void doFilterInternal(HttpServletRequest request,
@@ -0,0 +1,52 @@
package org.example.config;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
@Component
public class InstanceIdFilter extends OncePerRequestFilter {
public static final String HEADER = "X-Instance-Id";
private final String instanceId;
public InstanceIdFilter() {
this.instanceId = resolve();
}
private static String resolve() {
String id = firstNonBlank(
System.getenv("INSTANCE_ID"),
System.getenv("HOSTNAME"),
System.getProperty("HOSTNAME")
);
if (id == null) {
id = "unknown-" + UUID.randomUUID().toString().substring(0, 8);
}
return id;
}
private static String firstNonBlank(String... values) {
if (values == null) return null;
for (String v : values) {
if (v != null && !v.isBlank()) return v.trim();
}
return null;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
response.setHeader(HEADER, instanceId);
filterChain.doFilter(request, response);
}
}
@@ -38,7 +38,7 @@ public class HealthController {
} catch (Exception e){
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
}
return ResponseEntity.ok(Map.of("Status", "UP"));
return ResponseEntity.ok(Map.of("status", "ok"));
}
public void markNotReady() {
@@ -0,0 +1,7 @@
package org.example.exception;
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
}
@@ -58,6 +58,21 @@ public class GlobalExceptionHandler {
.body(body);
}
@ExceptionHandler(ConflictException.class)
public ResponseEntity<ErrorResponse> handleConflictException(
ConflictException ex,
HttpServletRequest request
) {
log.debug("Validation failed", ex);
String reqId = resolveRequestId(request);
ErrorResponse body = new ErrorResponse(
new ErrorDetail("conflict", "conflict", reqId)
);
return ResponseEntity.status(HttpStatus.CONFLICT)
.header("X-Request-Id", reqId)
.body(body);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationException(
MethodArgumentNotValidException ex,
@@ -80,7 +95,7 @@ public class GlobalExceptionHandler {
) {
String reqId = resolveRequestId(request);
ErrorResponse body = new ErrorResponse(
new ErrorDetail("bad_request", "Malformed JSON request body", reqId)
new ErrorDetail("invalid_request", "Malformed JSON request body", reqId)
);
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
@@ -213,7 +228,7 @@ public class GlobalExceptionHandler {
message = "Invalid UUID";
}
ErrorResponse body = new ErrorResponse(
new ErrorDetail("Invalid parameter", "Invalid UUID", reqId)
new ErrorDetail("invalid_request", "Invalid UUID", reqId)
);
// Error body: code invalid_request, request_id = reqId
return ResponseEntity
@@ -33,6 +33,9 @@ public class IdempotencyKey {
@Column(name = "idempotency_key", nullable = false)
private String idempotencyKey;
@Column(name = "request_hash", nullable = false)
private String requestHash;
@Column(name = "message_id", nullable = false)
private UUID messageId;
@@ -4,6 +4,7 @@ import lombok.RequiredArgsConstructor;
import org.example.dto.MessagePage;
import org.example.dto.create.CreateMessageDto;
import org.example.dto.update.UpdateMessageDto;
import org.example.exception.ConflictException;
import org.example.exception.ForbiddenException;
import org.example.exception.NotFoundException;
import org.example.model.IdempotencyKey;
@@ -21,6 +22,8 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.example.config.TokenHasher.sha256;
@Service
@RequiredArgsConstructor
public class MessageService {
@@ -41,12 +44,16 @@ public class MessageService {
}
String key = idempotencyKey.trim();
String hash = sha256(messageObject.getText());
Optional<IdempotencyKey> exists = idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
if (exists.isPresent()){
return messageRepository.findById(exists.get().getMessageId())
.orElseThrow(() -> new IllegalArgumentException("Сообщения нет"));
if (exists.isPresent()) {
var row = exists.get();
if (!row.getRequestHash().equals(hash)) {
throw new ConflictException("Idempotency key conflict");
}
return messageRepository.findById(row.getMessageId())
.orElseThrow(() -> new IllegalArgumentException("Jшибка при отправке сообщения") );
}
Message message = Message.builder()
@@ -63,6 +70,7 @@ public class MessageService {
.userId(senderId)
.chatId(chatId)
.idempotencyKey(key)
.requestHash(hash)
.messageId(message.getId())
.build()
);
+4 -5
View File
@@ -39,8 +39,10 @@ spring:
repositories:
enabled: false
server:
port: ${SERVER_PORT:8080}
server:
address: 0.0.0.0
port: 8080
shutdown: graceful
app:
session-ttl-seconds: ${SESSION_TTL_SECONDS:604800}
@@ -58,9 +60,6 @@ logging:
CommonsRequestLoggingFilter=DEBUG:
:servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver: DEBUG
server:
shutdown: graceful
management:
endpoints:
web:
@@ -0,0 +1,2 @@
ALTER TABLE idempotency_keys
ADD COLUMN IF NOT EXISTS request_hash VARCHAR(64) NOT NULL DEFAULT '';
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -eu
# scripts/ -> корень репо -> Lido
ROOT="$(CDPATH= cd -- "$(dirname "$0")/../Lido" && pwd)"
cd "$ROOT"
if [ ! -f docker-compose.yml ] && [ ! -f compose.yaml ] && [ ! -f compose.yml ]; then
echo "compose file not found in $ROOT" >&2
exit 1
fi
CID="$(docker compose ps -q api | head -n 1)"
if [ -z "$CID" ]; then
echo "no api replica found" >&2
exit 1
fi
docker stop "$CID"
exit 0