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
@@ -2,40 +2,52 @@ 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.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.config.SessionProperties;
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.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
@Slf4j
@RequiredArgsConstructor
@Service
public class SessionService {
private static final String SESSIONS = "sessions";
private final TokenGenerator tokenGenerator;
private final TokenHasher tokenHasher;
private final SessionProperties sessionProperties;
private final SessionRepository sessionRepository;
private final SessionMapper sessionMapper;
private final CacheManager cacheManager;
private final ExecutorService cacheEvictExecutor;
@Transactional
public SessionDTO createSession(UserDTO userDTO) {
String token = tokenGenerator.generate();
Session session = sessionRepository.save(buildSession(userDTO,token));
return toSessionDTO(session, token, userDTO);
return sessionMapper.toSessionDTO(session, token, userDTO);
}
@Cacheable(value = SESSIONS, key = "@tokenHasher.hash(#token)")
@Transactional(readOnly = true)
public SessionRecord requireActive(String token) {
Session s = sessionRepository.findByTokenHash(sha256(token))
Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token))
.filter(x -> x.getRevokedAt() == null)
.filter(x -> x.getExpiresAt().isAfter(Instant.now()))
.orElseThrow(() -> new UnauthorizedException("Invalid or expired session"));
@@ -46,35 +58,29 @@ public class SessionService {
public void revoke(UUID sessionId) {
sessionRepository.findById(sessionId).ifPresent(s -> {
if (s.getRevokedAt() == null) {
s.setRevokedAt(Instant.now());
s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
}
String key = tokenHasher.hash(s.getTokenHash());
cacheEvictExecutor.submit(() -> {
try {
Cache cache = cacheManager.getCache(SESSIONS);
if (cache != null) {
cache.evict(key);
}
} catch (RuntimeException e) {
log.warn("Cache EVICT failed (sessions): {}", e.getMessage());
}
});
});
}
private static byte[] sha256(String token) {
try {
return MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 not available", e);
}
}
private Session buildSession(UserDTO userDTO, String token) {
Session session = new Session();
session.setUserId(userDTO.getId());
session.setTokenHash(sha256(token));
session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()));
session.setTokenHash(tokenHasher.sha256(token));
session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS));
return session;
}
private SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO) {
return new SessionDTO()
.token(tokenRaw)
.tokenType(SessionDTO.TokenTypeEnum.BEARER)
.expiresAt(session.getExpiresAt())
.user(userDTO);
}
public record SessionRecord(UUID sessionId, UUID userId) {}
}