tasks for 4

This commit is contained in:
EgorAnti
2026-10-21 20:10:27 +03:00
parent 7565b65997
commit a70992ccdb
20 changed files with 617 additions and 41 deletions
@@ -0,0 +1,77 @@
package com.example.mtusi_messenger.cache;
import com.example.mtusi_messenger.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Component
public class UserCache {
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
private static final String KEY_PREFIX = "messenger:user:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final Duration ttl;
public UserCache(
StringRedisTemplate redis,
ObjectMapper mapper,
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("User cache TTL must be positive");
}
this.redis = redis;
this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds);
}
public Optional<User> find(UUID userId) {
try {
String value = redis.opsForValue().get(key(userId));
if (value == null) {
return Optional.empty();
}
return Optional.of(mapper.readValue(value, User.class));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
return Optional.empty();
} catch (JsonProcessingException e) {
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
}
public void put(User user) {
try {
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; user was not cached");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize user cache entry", e);
}
}
public void evict(UUID userId) {
try {
redis.delete(key(userId));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; cache eviction was skipped");
}
}
private String key(UUID userId) {
return KEY_PREFIX + userId;
}
}
@@ -21,7 +21,7 @@ public class PostgresChatRepository implements ChatRepository {
}
@Override
@Transactional
@Transactional(timeout = 5)
public Chat save(Chat chat) {
jdbc.update("""
INSERT INTO chats (id, title, created_at)
@@ -2,12 +2,14 @@ package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.repository.UserRepository;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.dao.DataAccessException;
import java.util.List;
@@ -27,7 +29,12 @@ public class DatabaseAuthenticationProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = String.valueOf(authentication.getCredentials());
var stored = users.findCredentialsByUsername(username);
final java.util.Optional<UserRepository.UserCredentials> stored;
try {
stored = users.findCredentialsByUsername(username);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
.filter(hash -> hash.startsWith("$argon2"))
.orElse(dummyPasswordHash);
@@ -7,6 +7,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.web.AuthenticationEntryPoint;
import java.io.IOException;
@@ -27,11 +28,19 @@ public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
AuthenticationException exception
) throws IOException {
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
boolean unavailable = exception instanceof AuthenticationServiceException;
response.setStatus(unavailable
? HttpServletResponse.SC_SERVICE_UNAVAILABLE
: HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("WWW-Authenticate", challenge);
if (!unavailable) {
response.setHeader("WWW-Authenticate", challenge);
}
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
new ErrorResponse.ErrorBody("unauthorized", "Authentication required", requestId)));
new ErrorResponse.ErrorBody(
unavailable ? "unavailable" : "unauthorized",
unavailable ? "Authentication service temporarily unavailable" : "Authentication required",
requestId)));
}
}
@@ -1,11 +1,14 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.cache.UserCache;
import com.example.mtusi_messenger.model.Session;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.repository.SessionRepository;
import com.example.mtusi_messenger.repository.UserRepository;
import com.example.mtusi_messenger.security.SessionPrincipal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
@@ -24,11 +27,13 @@ public class AuthenticationService {
private final UserRepository users;
private final SessionRepository sessions;
private final UserCache userCache;
private final long ttlSeconds;
public AuthenticationService(
UserRepository users,
SessionRepository sessions,
UserCache userCache,
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
@@ -36,6 +41,7 @@ public class AuthenticationService {
}
this.users = users;
this.sessions = sessions;
this.userCache = userCache;
this.ttlSeconds = ttlSeconds;
}
@@ -54,16 +60,28 @@ public class AuthenticationService {
public SessionPrincipal authenticateBearer(String token) {
byte[] tokenHash = hashToken(token);
UUID userId = sessions.findActiveUserId(tokenHash)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
User user = users.findById(userId)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
return new SessionPrincipal(user, tokenHash);
try {
UUID userId = sessions.findActiveUserId(tokenHash)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
User user = userCache.find(userId).orElseGet(() -> {
User loaded = users.findById(userId)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
userCache.put(loaded);
return loaded;
});
return new SessionPrincipal(user, tokenHash);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
public void revoke(SessionPrincipal principal) {
if (!sessions.revoke(principal.tokenHash())) {
throw new BadCredentialsException("Invalid or expired session");
try {
if (!sessions.revoke(principal.tokenHash())) {
throw new BadCredentialsException("Invalid or expired session");
}
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
@@ -13,7 +13,7 @@ import java.util.*;
public class ChatService {
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
public synchronized Chat create(CreateChatRequest r, UUID caller) {
public Chat create(CreateChatRequest r, UUID caller) {
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
@@ -19,7 +19,7 @@ public class UserService {
this.users = users;
this.passwordEncoder = passwordEncoder;
}
public synchronized User create(CreateUserRequest r) {
public User create(CreateUserRequest r) {
String username = r.username(); String display = r.display_name();
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
String passwordHash = passwordEncoder.encode(r.password());
@@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.dao.DataAccessException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -27,6 +28,10 @@ public class GlobalExceptionHandler {
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
@ExceptionHandler(DataAccessException.class)
ResponseEntity<ErrorResponse> unavailable(DataAccessException e, HttpServletRequest req) {
return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req));
}
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
private ErrorResponse body(
+25
View File
@@ -8,8 +8,31 @@ spring:
password: ${DATABASE_PASSWORD:messenger}
hikari:
maximum-pool-size: ${DATABASE_POOL_SIZE:10}
minimum-idle: ${DATABASE_MIN_IDLE:2}
connection-timeout: 5000
validation-timeout: 2000
idle-timeout: 600000
max-lifetime: 1800000
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s}
timeout: ${REDIS_COMMAND_TIMEOUT:500ms}
lettuce:
pool:
max-active: ${REDIS_POOL_MAX_ACTIVE:8}
max-idle: ${REDIS_POOL_MAX_IDLE:8}
min-idle: ${REDIS_POOL_MIN_IDLE:0}
max-wait: ${REDIS_POOL_MAX_WAIT:500ms}
jdbc:
template:
query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5}
transaction:
default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5}
flyway:
enabled: true
@@ -31,3 +54,5 @@ messenger:
storage: postgres
session:
ttl-seconds: ${SESSION_TTL_SECONDS:3600}
cache:
user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300}