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; } }