package ru.mtuci.messenger.cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.UUID; /** * Кэш Bearer-сессий: session:{sha256(token)} -> userId, TTL = остаток жизни сессии. * Источник истины — таблица sessions; при ошибке Redis вызывающий идёт в PostgreSQL. */ @Component public class SessionCache { private static final Logger log = LoggerFactory.getLogger(SessionCache.class); private final StringRedisTemplate redis; public SessionCache(StringRedisTemplate redis) { this.redis = redis; } public Optional find(String tokenHash) { try { return Optional.ofNullable(redis.opsForValue().get(key(tokenHash))).map(UUID::fromString); } catch (DataAccessException exception) { log.warn("session cache bypass: {}", exception.getClass().getSimpleName()); return Optional.empty(); } } public void put(String tokenHash, UUID userId, Instant expiresAt) { Duration ttl = Duration.between(Instant.now(), expiresAt); if (ttl.isNegative() || ttl.isZero()) { return; } try { redis.opsForValue().set(key(tokenHash), userId.toString(), ttl); } catch (DataAccessException exception) { log.warn("session cache write skipped: {}", exception.getClass().getSimpleName()); } } public void evict(String tokenHash) { try { redis.delete(key(tokenHash)); } catch (DataAccessException exception) { log.warn("session cache evict skipped: {}", exception.getClass().getSimpleName()); } } private static String key(String tokenHash) { return "session:" + tokenHash; } }