concurrency

This commit is contained in:
2026-10-08 13:08:31 +03:00
parent b95197a6fc
commit 65bd58c409
42 changed files with 743 additions and 224 deletions
@@ -25,7 +25,7 @@ public class ChatController implements ChatsApi {
@Override
public ResponseEntity<ChatDTO> getChat(UUID chatId , @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.ok(chatService.getChat(principal.userId(), chatId));
return ResponseEntity.ok(chatService.getChatDTO(principal.userId(), chatId));
}
@Override
@@ -107,7 +107,7 @@ public interface ChatsApi {
* or Неожиданная ошибка без внутренних деталей (status code 500)
*/
@Operation(
operationId = "getChat",
operationId = "getChatDTO",
summary = "Получить доступный чат",
tags = { "Chats" },
responses = {
@@ -30,26 +30,26 @@ public interface HealthApi {
* or Неожиданная ошибка без внутренних деталей (status code 500)
*/
@Operation(
operationId = "liveness",
summary = "Процесс жив",
tags = { "Health" },
responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
})
}
operationId = "liveness",
summary = "Процесс жив",
tags = { "Health" },
responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
})
}
)
@RequestMapping(
method = RequestMethod.GET,
value = "/health/live",
produces = { "application/json" }
method = RequestMethod.GET,
value = "/health/live",
produces = { "application/json" }
)
ResponseEntity<HealthDTO> liveness(
);
@@ -61,29 +61,29 @@ public interface HealthApi {
* or Неожиданная ошибка без внутренних деталей (status code 500)
*/
@Operation(
operationId = "readiness",
summary = "Готов принимать трафик",
tags = { "Health" },
responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}),
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
}),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
})
}
operationId = "readiness",
summary = "Готов принимать трафик",
tags = { "Health" },
responses = {
@ApiResponse(responseCode = "200", description = "Успех", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = HealthDTO.class))
}),
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
}),
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))
})
}
)
@RequestMapping(
method = RequestMethod.GET,
value = "/health/ready",
produces = { "application/json" }
method = RequestMethod.GET,
value = "/health/ready",
produces = { "application/json" }
)
ResponseEntity<HealthDTO> readiness(
);
}
}
@@ -1,26 +1,24 @@
package ru.mtusi.messenger.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.HealthDTO;
import ru.mtusi.messenger.service.HealthService;
@RestController
@RequiredArgsConstructor
public class HealthController implements HealthApi {
private static final HealthDTO OK = createOk();
private final HealthService healthService;
@Override
public ResponseEntity<HealthDTO> liveness() {
return ResponseEntity.ok(OK);
return ResponseEntity.ok(healthService.liveness());
}
@Override
public ResponseEntity<HealthDTO> readiness() {
return ResponseEntity.ok(OK);
return ResponseEntity.ok(healthService.readiness());
}
private static HealthDTO createOk() {
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
}
}
}
@@ -5,6 +5,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.MessagePageDTO;
import ru.mtusi.messenger.security.SessionPrincipal;
@@ -18,8 +19,8 @@ public class MessageController implements MessagesApi {
private final MessageService messageService;
@Override
public ResponseEntity<MessageDTO> createMessage(UUID chatId, MessageDTO messageDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, messageDTO));
public ResponseEntity<MessageDTO> createMessage(UUID chatId, CreateMessageDTO createMessageDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED).body(messageService.createMessage(principal.userId(), chatId, createMessageDTO));
}
@Override
@@ -6,6 +6,7 @@
package ru.mtusi.messenger.controller;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.ErrorDTO;
import ru.mtusi.messenger.dto.MessagePageDTO;
@@ -77,8 +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 = "MessageDTO", description = "", required = true)
@Valid @RequestBody MessageDTO messageDTO,
@Parameter(name = "CreateMessageDTO", description = "", required = true)
@Valid @RequestBody CreateMessageDTO createMessageDTO,
@AuthenticationPrincipal SessionPrincipal principal
);
@@ -0,0 +1,147 @@
package ru.mtusi.messenger.controller.controllerAdvice;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.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 ru.mtusi.messenger.config.properties.RateLimitProperties;
import ru.mtusi.messenger.dto.ErrorDTO;
import ru.mtusi.messenger.dto.ErrorErrorDTO;
import ru.mtusi.messenger.exception.*;
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {
private final RateLimitProperties limitProperties;
private final ApiErrorFactory errors;
@ExceptionHandler(InvalidRequestException.class)
public ResponseEntity<ErrorDTO> invalidRequest(InvalidRequestException e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req);
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorDTO> unauthorized(UnauthorizedException e, HttpServletRequest req) {
String scheme = req.getRequestURI().equals("/api/v1/auth/sessions")
? "Basic" : "Bearer";
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.header("WWW-Authenticate", scheme + " realm=\"messenger\"")
.body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req));
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorDTO> notFound(NotFoundException e, HttpServletRequest req) {
return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req);
}
@ExceptionHandler(ConflictException.class)
public ResponseEntity<ErrorDTO> conflict(ConflictException e, HttpServletRequest req) {
return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req);
}
@ExceptionHandler(PayloadTooLargeException.class)
public ResponseEntity<ErrorDTO> payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) {
return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorDTO> validation(MethodArgumentNotValidException e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ErrorDTO> unreadable(Exception e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req);
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ErrorDTO> missingParam(Exception e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<ErrorDTO> typeMismatch(Exception e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity<ErrorDTO> mediaType(Exception e, HttpServletRequest req) {
return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE,
"Unsupported media type", req);
}
@ExceptionHandler(HandlerMethodValidationException.class)
public ResponseEntity<ErrorDTO> methodValidation(Exception e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
"Validation failed", req);
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<ErrorDTO> methodNotAllowed(Exception e, HttpServletRequest req) {
return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
"Method not allowed", req);
}
@ExceptionHandler(RateLimitedException.class)
public ResponseEntity<ErrorDTO> rateLimited(RateLimitedException e, HttpServletRequest req) {
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS)
.header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds()))
.body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req));
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorDTO> constraint(ConstraintViolationException e, HttpServletRequest req) {
return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
"Validation failed", req);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDTO> fallback(Exception e, HttpServletRequest req) {
return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
"Internal error", req);
}
@ExceptionHandler(ServiceUnavailableException.class)
public ResponseEntity<ErrorDTO> serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) {
return respond(HttpStatus.SERVICE_UNAVAILABLE,
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
e.getMessage(), req);
}
@ExceptionHandler({
CannotCreateTransactionException.class,
DataAccessResourceFailureException.class
})
public ResponseEntity<ErrorDTO> dependencyUnavailable(Exception e, HttpServletRequest req) {
return respond(HttpStatus.SERVICE_UNAVAILABLE,
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
"Dependency unavailable", req);
}
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<ErrorDTO> dataAccess(DataAccessException e, HttpServletRequest req) {
return respond(HttpStatus.INTERNAL_SERVER_ERROR,
ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
"Database error", req);
}
private ResponseEntity<ErrorDTO> respond(HttpStatus status,
ErrorErrorDTO.CodeEnum code,
String message,
HttpServletRequest req) {
return ResponseEntity.status(status).body(errors.error(code, message, req));
}
}