Files
mtusi2026lab2/backend/src/main/java/ru/mtuci/messenger/web/ApiAdvice.java
T
ivanstorozhev 0fd4f49861
Skeleton contracts / contracts (pull_request) Canceled after 0s
## Лабораторная 2
Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен
Что реализовано и что перенесено: Spring Boot API мессенджера. Код lab1 не копировался, взята только модель пользователя, чата и сообщения. PostgreSQL хранит пользователей, чаты, участников, сообщения и сессии. Redis кэширует разбор Bearer-токена и обходится при отказе. Пароли — Argon2id. Миграции Liquibase, модели из OpenAPI, MapStruct.
Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
Результаты проверок и ссылка на REPORT.md: подробности в REPORT.md.
make check — PASS: offline skeleton structure, local refs and Python syntax.
make test — PASS: lab2 public API scenario.
make test-persistence ACTION_SCRIPT=scripts/restart.sh — PASS: persistence preserved confirmed data and existing session.
mvn -q test в backend/ — пройден, включая гонку username, откат чата, expiry, logout, недоступность Redis и PostgreSQL, EXPLAIN индекса (evidence/explain-messages.txt).
Ограничения / известные ошибки: трек 5 не делался. Если Redis жив, а удаление ключа при logout не прошло, кэш может жить до своего TTL; при недоступном Redis сессия читается из PostgreSQL. История сообщений не кэшируется. Bean Validation сгенерированных моделей считает Java char, сервис проверяет code points.
Источники и использование ИИ: контракт contracts/openapi.json и contracts/README.md; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Liquibase, Actuator, MapStruct 1.6.3, OpenAPI Generator 7.17.0, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, Testcontainers. Реализация собрана в Cursor.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
2026-10-23 10:40:29 +03:00

91 lines
5.1 KiB
Java

package ru.mtuci.messenger.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import ru.mtuci.messenger.api.model.Error;
import ru.mtuci.messenger.api.model.ErrorError;
import ru.mtuci.messenger.exception.ApiException;
import ru.mtuci.messenger.exception.UnauthorizedException;
@RestControllerAdvice
public class ApiAdvice {
private static final Logger log = LoggerFactory.getLogger(ApiAdvice.class);
@ExceptionHandler(ApiException.class)
public ResponseEntity<Error> handleApi(HttpServletRequest request, HttpServletResponse response, ApiException exception) {
log.info("api error code={}", exception.code().getValue());
String challenge = exception instanceof UnauthorizedException unauthorized ? unauthorized.challenge() : null;
return response(request, response, exception.status(), exception.code(), exception.getMessage(), challenge);
}
@ExceptionHandler({
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
ConstraintViolationException.class,
HandlerMethodValidationException.class,
MethodArgumentTypeMismatchException.class,
MissingServletRequestParameterException.class,
HttpRequestMethodNotSupportedException.class
})
public ResponseEntity<Error> handleInvalid(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.info("invalid request type={}", exception.getClass().getSimpleName());
return response(request, response, HttpStatus.BAD_REQUEST, ErrorError.CodeEnum.INVALID_REQUEST, "Некорректный запрос", null);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity<Error> handleMedia(HttpServletRequest request, HttpServletResponse response) {
return response(request, response, HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorError.CodeEnum.UNSUPPORTED_MEDIA_TYPE,
"Неподдерживаемый тип содержимого", null);
}
@ExceptionHandler({NoResourceFoundException.class, NoHandlerFoundException.class})
public ResponseEntity<Error> handleMissing(HttpServletRequest request, HttpServletResponse response) {
return response(request, response, HttpStatus.NOT_FOUND, ErrorError.CodeEnum.NOT_FOUND, "Объект не найден", null);
}
@ExceptionHandler({DataAccessException.class, CannotCreateTransactionException.class})
public ResponseEntity<Error> handleDataAccess(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.warn("data access failure type={}", exception.getClass().getSimpleName());
return response(request, response, HttpStatus.SERVICE_UNAVAILABLE, ErrorError.CodeEnum.UNAVAILABLE,
"Сервис временно недоступен", null);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Error> handleUnexpected(HttpServletRequest request, HttpServletResponse response, Exception exception) {
log.error("unexpected failure type={}", exception.getClass().getName(), exception);
return response(request, response, HttpStatus.INTERNAL_SERVER_ERROR, ErrorError.CodeEnum.INTERNAL_ERROR,
"Внутренняя ошибка", null);
}
private ResponseEntity<Error> response(HttpServletRequest request, HttpServletResponse response, HttpStatus status,
ErrorError.CodeEnum code, String message, String challenge) {
String requestId = RequestIdFilter.id(request);
response.setHeader(RequestIdFilter.HEADER, requestId);
HttpHeaders headers = new HttpHeaders();
if (challenge != null) {
headers.set(HttpHeaders.WWW_AUTHENTICATE, challenge);
}
return new ResponseEntity<>(new Error(new ErrorError(code, message, requestId)), headers, status);
}
}