init commit

This commit is contained in:
2026-10-22 20:59:59 +03:00
parent ec540a1a72
commit 1fddc0e76c
95 changed files with 5668 additions and 27 deletions
@@ -0,0 +1,36 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import ru.mtusi.messenger.dto.SessionDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.security.BasicCredentials;
import ru.mtusi.messenger.security.SessionPrincipal;
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserService userService;
private final SessionService sessionService;
public SessionDTO login(String authorizationHeader, long contentLength) {
if (contentLength > 0) {
throw new InvalidRequestException("Request body is not allowed");
}
var creds = BasicCredentials.parse(authorizationHeader);
UserDTO userDTO = userService.authenticate(creds.username(), creds.password());
return sessionService.createSession(userDTO);
}
public void logout() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !(auth.getPrincipal() instanceof SessionPrincipal sp)) {
throw new UnauthorizedException("No active session");
}
sessionService.revoke(sp.sessionId());
}
}
@@ -0,0 +1,130 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.ChatPageDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.mapper.ChatMapper;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.validation.ChatValidator;
import ru.mtusi.messenger.util.CursorCodec;
import java.util.*;
@Service
@Slf4j
@RequiredArgsConstructor
public class ChatService {
private final ChatMapper chatMapper;
private final ChatValidator chatValidator;
private final ChatRepository chatRepository;
@Transactional
public ChatDTO createChat(UUID caller, CreateChatDTO createChatDTO) {
Set<User> members = chatValidator.validateCreate(caller, createChatDTO);
Chat chat = buildChat(createChatDTO, members);
chat = persistChat(chat);
return chatMapper.toChatDto(chat);
}
private Chat buildChat(CreateChatDTO createChatDTO, Set<User> members) {
Chat chat = chatMapper.toChat(createChatDTO);
chat.setMembers(members);
return chat;
}
private Chat persistChat(Chat chat) {
try {
return chatRepository.saveAndFlush(chat);
} catch (DataIntegrityViolationException e) {
throw new InvalidRequestException("Cannot create chat: invalid data");
}
}
@Transactional(readOnly = true)
public ChatDTO getChatDTO(UUID caller, UUID chatId) {
Chat chat = requireChatForMember(caller, chatId);
return chatMapper.toChatDto(chat);
}
@Transactional(readOnly = true)
public Chat getChat(UUID caller, UUID chatId) {
return requireChatForMember(caller, chatId);
}
private Chat requireChatForMember(UUID caller, UUID chatId) {
Chat chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) {
throw new NotFoundException("Chat not found");
}
return chat;
}
@Transactional(readOnly = true)
public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) {
int size = resolveSize(limit);
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
List<Chat> rows = loadChatPage(userId, decoded, size);
return buildPage(rows, size);
}
private int resolveSize(Integer limit) {
return (limit == null) ? 50 : limit;
}
private List<Chat> loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) {
if (cursor == null) {
return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1));
}
return chatRepository.findPageByMemberAfterCursor(
userId,
cursor.boundary().createdAt(),
cursor.boundary().id(),
Pageable.ofSize(size + 1));
}
private CursorCodec.Cursor parseChatsCursor(String cursor) {
if (cursor == null)
return null;
if (cursor.isEmpty())
throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() != null)
throw new InvalidRequestException("Invalid cursor");
return decoded;
}
private ChatPageDTO buildPage(List<Chat> rows, int size) {
List<ChatDTO> items = rows.stream()
.limit(size)
.map(chatMapper::toChatDto)
.toList();
ChatPageDTO page = new ChatPageDTO();
page.setItems(items);
page.setNextCursor(buildNextCursor(rows, size));
return page;
}
private String buildNextCursor(List<Chat> rows, int size) {
if (rows.size() <= size) {
return null;
}
Chat last = rows.get(size - 1);
return CursorCodec.encode(null, boundaryOf(last));
}
private CursorCodec.PageBoundary boundaryOf(Chat chat) {
return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId());
}
}
@@ -0,0 +1,51 @@
package ru.mtusi.messenger.service;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import ru.mtusi.messenger.dto.HealthDTO;
import ru.mtusi.messenger.exception.ServiceUnavailableException;
import javax.sql.DataSource;
@Service
@RequiredArgsConstructor
public class HealthService {
private final JdbcTemplate jdbcTemplate;
private final DataSource dataSource;
public HealthDTO readiness() {
requirePoolAvailable();
requireDatabaseReachable();
return ok();
}
public HealthDTO liveness() {
return ok();
}
private void requirePoolAvailable() {
if (dataSource instanceof HikariDataSource hikari) {
var pool = hikari.getHikariPoolMXBean();
if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) {
throw new ServiceUnavailableException("Database connection pool exhausted");
}
}
}
private void requireDatabaseReachable() {
try {
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
} catch (Exception e) {
throw new ServiceUnavailableException("Database unavailable");
}
}
private HealthDTO ok() {
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
}
}
@@ -0,0 +1,63 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.model.IdempotencyKey;
import ru.mtusi.messenger.repository.IdempotencyRepository;
import ru.mtusi.messenger.util.converter.IdempotencyPayloadConverter;
import ru.mtusi.messenger.validation.IdempotencyValidator;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.UUID;
import java.util.function.Supplier;
@Service
@RequiredArgsConstructor
public class IdempotencyService {
private final IdempotencyRepository idempotencyRepository;
private final IdempotencyPayloadConverter converter;
private final IdempotencyValidator validator;
@Transactional
public <T> T execute(UUID userId, String method, UUID chatId, String key,
Object requestBody, Class<T> responseType, Supplier<T> action) {
validator.validateKey(key);
String hash = hashRequest(requestBody);
int claimed = idempotencyRepository.tryClaim(userId, method, chatId, key, hash);
if (claimed == 0) {
return replay(userId, method, chatId, key, hash, responseType);
}
T result = action.get();
idempotencyRepository.commitResponse(userId, method, chatId, key, 201, converter.toJson(result));
return result;
}
private <T> T replay(UUID userId, String method, UUID chatId, String key,
String hash, Class<T> responseType) {
IdempotencyKey stored = idempotencyRepository
.findByUserIdAndMethodAndChatIdAndIdempotencyKey(userId, method, chatId, key)
.orElseThrow(() -> new IllegalStateException("Idempotency row not visible after conflict"));
if (!stored.getRequestHash().equals(hash))
throw new ConflictException("Idempotency-Key reused with a different request body");
if (stored.getStatusCode() == null || stored.getStatusCode() != 201)
throw new ConflictException("Idempotency-Key has unexpected status");
return converter.fromJson(stored.getResponseBody(), responseType);
}
private String hashRequest(Object body) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(converter.toJson(body).getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (Exception e) {
throw new IllegalStateException("Cannot hash request body", e);
}
}
}
@@ -0,0 +1,116 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.properties.AppProperties;
import ru.mtusi.messenger.dto.CreateMessageDTO;
import ru.mtusi.messenger.dto.MessageDTO;
import ru.mtusi.messenger.dto.MessagePageDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.exception.PayloadTooLargeException;
import ru.mtusi.messenger.mapper.MessageMapper;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.Message;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.MessageRepository;
import ru.mtusi.messenger.util.CursorCodec;
import ru.mtusi.messenger.service.IdempotencyService;
import java.util.List;
import java.util.UUID;
@Service
@Slf4j
@RequiredArgsConstructor
public class MessageService {
private final IdempotencyService idempotencyService;
private final MessageRepository messageRepository;
private final ChatService chatService;
private final UserService userService;
private final MessageMapper messageMapper;
private final AppProperties appProperties;
@Transactional
public MessageDTO createMessage(UUID senderId, UUID chatId, CreateMessageDTO dto, String idempotencyKey) {
Chat chat = chatService.getChat(senderId, chatId);
return idempotencyService.execute(senderId, "POST", chatId, idempotencyKey, dto, MessageDTO.class,
() -> doCreate(senderId, chatId, dto, chat));
}
private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) {
validateCreate(chatId, dto);
User sender = userService.getReferenceUserById(senderId);
Message message = buildMessage(dto, sender, chat);
try {
message = messageRepository.saveAndFlush(message);
} catch (DataIntegrityViolationException e) {
throw new NotFoundException("Cannot create message: referenced entity is missing");
}
log.info("Created message id={} in chat={}", message.getId(), chatId);
return messageMapper.toMessageDTO(message);
}
private void validateCreate(UUID chatId, CreateMessageDTO dto) {
if (dto.getText() == null || dto.getText().isBlank()) {
throw new InvalidRequestException("Empty text");
}
if (messageRepository.countByChatId(chatId) >= appProperties.maxMessagesPerChat()) {
throw new PayloadTooLargeException("Chat history limit reached");
}
}
private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) {
Message message = messageMapper.toMessage(createMessageDTO);
message.setChat(chat);
message.setSender(sender);
return message;
}
@Transactional(readOnly = true)
public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) {
int size = (limit == null) ? 50 : limit;
chatService.getChatDTO(userId, chatId);
CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId);
List<Message> rows = (decoded == null) ? messageRepository.findPageByChat(chatId, Pageable.ofSize(size + 1))
: messageRepository.findPageByChatAfterCursor(chatId, decoded.boundary().createdAt(), decoded.boundary().id(), Pageable.ofSize(size + 1));
return buildPage(rows, size, chatId);
}
private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) {
if (cursor == null)
return null;
if (cursor.isEmpty())
throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId))
throw new InvalidRequestException("Cursor from another chat");
return decoded;
}
private MessagePageDTO buildPage(List<Message> rows, int size, UUID chatId) {
List<MessageDTO> items = rows.stream()
.limit(size)
.map(messageMapper::toMessageDTO)
.toList();
MessagePageDTO page = new MessagePageDTO();
page.setItems(items);
page.setNextCursor(buildNextCursor(rows, size, chatId));
return page;
}
private String buildNextCursor(List<Message> rows, int size, UUID chatId) {
if (rows.size() <= size) {
return null;
}
Message last = rows.get(size - 1);
return CursorCodec.encode(chatId, new CursorCodec.PageBoundary(
last.getCreatedAt(), last.getId()));
}
}
@@ -0,0 +1,65 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.cache.CacheHealthTracker;
import ru.mtusi.messenger.repository.SessionRepository;
@Slf4j
@Service
@RequiredArgsConstructor
public class SessionCacheService {
public static final String SESSIONS = "sessions";
private final SessionRepository sessionRepository;
private final CacheManager cacheManager;
private final CacheHealthTracker cacheHealthTracker;
@Cacheable(value = SESSIONS, key = "#hex", unless = "#result == null")
@Transactional(readOnly = true)
public SessionService.SessionRecord lookupByHash(String hex) {
byte[] hash = hexToBytes(hex);
return sessionRepository.findByTokenHash(hash)
.filter(s -> s.getRevokedAt() == null)
.map(s -> new SessionService.SessionRecord(
s.getId(), s.getUserId(), s.getExpiresAt()))
.orElse(null);
}
@CacheEvict(value = SESSIONS, key = "#hex")
public void evict(String hex) {
}
public void dropCacheIfStale() {
if (!cacheHealthTracker.consumeStale()) {
return;
}
try {
Cache cache = cacheManager.getCache(SESSIONS);
if (cache != null) {
cache.clear();
}
log.info("Cache '{}' cleared after stale flag", SESSIONS);
} catch (RuntimeException e) {
log.warn("Cache clear failed: {}", e.getMessage());
cacheHealthTracker.markStale();
}
}
private static byte[] hexToBytes(String hex) {
int len = hex.length();
byte[] out = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
out[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return out;
}
}
@@ -0,0 +1,81 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.properties.SessionProperties;
import ru.mtusi.messenger.dto.SessionDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.mapper.SessionMapper;
import ru.mtusi.messenger.model.Session;
import ru.mtusi.messenger.repository.SessionRepository;
import ru.mtusi.messenger.util.TokenGenerator;
import ru.mtusi.messenger.util.TokenHasher;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Slf4j
@RequiredArgsConstructor
@Service
public class SessionService {
private final TokenGenerator tokenGenerator;
private final TokenHasher tokenHasher;
private final SessionProperties sessionProperties;
private final SessionRepository sessionRepository;
private final SessionMapper sessionMapper;
private final SessionCacheService sessionCacheService;
@Transactional
public SessionDTO createSession(UserDTO userDTO) {
String token = tokenGenerator.generate();
Session session = sessionRepository.save(buildSession(userDTO,token));
return sessionMapper.toSessionDTO(session, token, userDTO);
}
public SessionRecord requireActive(String token) {
sessionCacheService.dropCacheIfStale();
String hex = tokenHasher.hash(token);
SessionRecord record = sessionCacheService.lookupByHash(hex);
requireNotExpired(record, hex);
return record;
}
private void requireNotExpired(SessionRecord record, String hex) {
if (record == null || isExpired(record)) {
sessionCacheService.evict(hex);
throw new UnauthorizedException("Invalid or expired session");
}
}
private boolean isExpired(SessionRecord record) {
return record.expiresAt().isBefore(Instant.now());
}
@Transactional
public void revoke(UUID sessionId) {
sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict);
}
private void markRevokedAndEvict(Session session) {
if (session.getRevokedAt() == null) {
session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
}
sessionCacheService.evict(tokenHasher.hash(session.getTokenHash()));
}
private Session buildSession(UserDTO userDTO, String token) {
Session session = new Session();
session.setUserId(userDTO.getId());
session.setTokenHash(tokenHasher.sha256(token));
session.setExpiresAt(Instant.now()
.plus(sessionProperties.ttl())
.truncatedTo(ChronoUnit.MILLIS));
return session;
}
public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {}
}
@@ -0,0 +1,84 @@
package ru.mtusi.messenger.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.CreateUserDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.mapper.UserMapper;
import ru.mtusi.messenger.model.User;
import ru.mtusi.messenger.repository.UserRepository;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {
private final PasswordEncoder passwordEncoder;
private final UserMapper userMapper;
private final UserRepository userRepository;
@Transactional
public Set<User> requireUsers(Collection<UUID> ids) {
Set<UUID> uniqueIds = new HashSet<>(ids);
Set<User> users = userRepository.findAllByIdForShare(uniqueIds);
if (users.size() != uniqueIds.size()) {
throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users));
}
return users;
}
private Set<UUID> findMissing(Set<UUID> requested, Set<User> found) {
Set<UUID> foundIds = found.stream()
.map(User::getId)
.collect(Collectors.toSet());
Set<UUID> missing = new HashSet<>(requested);
missing.removeAll(foundIds);
return missing;
}
@Transactional(readOnly = true)
public UserDTO authenticate(String username, String password) {
User user = userRepository.findByUsername(username).orElseThrow(() -> new UnauthorizedException("Bad credentials"));
if (!passwordEncoder.matches(password, user.getPasswordHash())) {
throw new UnauthorizedException("Bad credentials");
}
return userMapper.toUserDto(user);
}
@Transactional
public UserDTO registerUser(CreateUserDTO createUserDTO) {
User user = userMapper.toUser(createUserDTO);
user.setPasswordHash(passwordEncoder.encode(createUserDTO.getPassword()));
try {
return userMapper.toUserDto(userRepository.saveAndFlush(user));
} catch (DataIntegrityViolationException exception) {
throw new ConflictException("Username already exists");
}
}
@Transactional(readOnly = true)
public UserDTO currentUser(UUID userId) {
return userMapper.toUserDto(userRepository.findById(userId).orElseThrow(() ->
new NotFoundException("User not found")
));
}
@Transactional
public User getReferenceUserById(UUID senderId) {
return userRepository.getReferenceById(senderId);
}
}