forked from mtusi2026/mtusi2026lab2
Добавить мессенджер на Java с PostgreSQL и сессиями в Redis.
Данные и действующий токен переживают рестарт, сессии хранятся в Redis с AOF. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
final class ApiException extends RuntimeException {
|
||||
final int status;
|
||||
final String code;
|
||||
final String clientMessage;
|
||||
final String challenge;
|
||||
|
||||
private ApiException(int status, String code, String clientMessage, String challenge) {
|
||||
super(code);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.clientMessage = clientMessage;
|
||||
this.challenge = challenge;
|
||||
}
|
||||
|
||||
static ApiException invalid(String message) {
|
||||
return new ApiException(400, "invalid_request", message, null);
|
||||
}
|
||||
|
||||
static ApiException unauthorized(String challenge) {
|
||||
return new ApiException(401, "unauthorized", "Нет действительной идентификации", challenge);
|
||||
}
|
||||
|
||||
static ApiException notFound() {
|
||||
return new ApiException(404, "not_found", "Объект не найден", null);
|
||||
}
|
||||
|
||||
static ApiException conflict() {
|
||||
return new ApiException(409, "conflict", "Имя пользователя уже занято", null);
|
||||
}
|
||||
|
||||
static ApiException tooLarge() {
|
||||
return new ApiException(413, "payload_too_large", "Тело запроса слишком большое", null);
|
||||
}
|
||||
|
||||
static ApiException dependency() {
|
||||
return new ApiException(503, "unavailable", "Зависимость недоступна", null);
|
||||
}
|
||||
|
||||
static ApiException shuttingDown() {
|
||||
return new ApiException(503, "unavailable", "Сервер останавливается", null);
|
||||
}
|
||||
|
||||
static ApiException internalError() {
|
||||
return new ApiException(500, "internal_error", "Внутренняя ошибка", null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
final class Config {
|
||||
final String host;
|
||||
final int port;
|
||||
final String appEnv;
|
||||
final String jdbcUrl;
|
||||
final String dbUser;
|
||||
final String dbPassword;
|
||||
final String redisUrl;
|
||||
final int sessionTtlSeconds;
|
||||
final int bcryptCost;
|
||||
|
||||
Config(
|
||||
String host,
|
||||
int port,
|
||||
String appEnv,
|
||||
String jdbcUrl,
|
||||
String dbUser,
|
||||
String dbPassword,
|
||||
String redisUrl,
|
||||
int sessionTtlSeconds,
|
||||
int bcryptCost) {
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.appEnv = appEnv;
|
||||
this.jdbcUrl = jdbcUrl;
|
||||
this.dbUser = dbUser;
|
||||
this.dbPassword = dbPassword;
|
||||
this.redisUrl = redisUrl;
|
||||
this.sessionTtlSeconds = sessionTtlSeconds;
|
||||
this.bcryptCost = bcryptCost;
|
||||
}
|
||||
|
||||
static Config fromEnvironment() {
|
||||
String host = env("APP_HOST", "0.0.0.0");
|
||||
int port = parsePort(env("APP_PORT", "8080"));
|
||||
String appEnv = env("APP_ENV", "lab");
|
||||
int ttl = parsePositive("SESSION_TTL_SECONDS", env("SESSION_TTL_SECONDS", "3600"));
|
||||
int cost = parsePositive("BCRYPT_COST", env("BCRYPT_COST", "10"));
|
||||
String store = env("SESSION_STORE", "redis");
|
||||
if (!store.equals("redis")) {
|
||||
fail("SESSION_STORE");
|
||||
}
|
||||
String database = secret("DATABASE_URL", "DATABASE_URL_FILE");
|
||||
String redis = secret("REDIS_URL", "CACHE_URL_FILE");
|
||||
Jdbc jdbc = jdbc(database);
|
||||
return new Config(host, port, appEnv, jdbc.url, jdbc.user, jdbc.password, redis.trim(), ttl, cost);
|
||||
}
|
||||
|
||||
private static String env(String name, String fallback) {
|
||||
String value = System.getenv(name);
|
||||
if (value == null || value.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private static String secret(String directName, String fileName) {
|
||||
String direct = System.getenv(directName);
|
||||
if (direct != null && !direct.isBlank()) {
|
||||
return direct.trim();
|
||||
}
|
||||
String file = System.getenv(fileName);
|
||||
if (file == null || file.isBlank()) {
|
||||
fail(fileName);
|
||||
}
|
||||
try {
|
||||
String value = Files.readString(Path.of(file)).trim();
|
||||
if (value.isEmpty()) {
|
||||
fail(fileName);
|
||||
}
|
||||
return value;
|
||||
} catch (Exception e) {
|
||||
fail(fileName);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static int parsePort(String raw) {
|
||||
try {
|
||||
int value = Integer.parseInt(raw);
|
||||
if (value < 0 || value > 65535) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return value;
|
||||
} catch (NumberFormatException e) {
|
||||
fail("APP_PORT");
|
||||
return 8080;
|
||||
}
|
||||
}
|
||||
|
||||
private static int parsePositive(String name, String raw) {
|
||||
try {
|
||||
int value = Integer.parseInt(raw);
|
||||
if (value < 1) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return value;
|
||||
} catch (NumberFormatException e) {
|
||||
fail(name);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static void fail(String name) {
|
||||
System.err.println("event=config_failed name=" + name);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
private record Jdbc(String url, String user, String password) {
|
||||
}
|
||||
|
||||
private static Jdbc jdbc(String raw) {
|
||||
String value = raw.trim();
|
||||
try {
|
||||
if (value.startsWith("jdbc:postgresql:")) {
|
||||
return fromJdbc(value);
|
||||
}
|
||||
if (value.startsWith("postgres://")) {
|
||||
value = "postgresql://" + value.substring("postgres://".length());
|
||||
}
|
||||
if (!value.startsWith("postgresql://")) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
URI uri = URI.create(value);
|
||||
String userInfo = uri.getRawUserInfo();
|
||||
if (userInfo == null || !userInfo.contains(":")) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int colon = userInfo.indexOf(':');
|
||||
String user = URLDecoder.decode(userInfo.substring(0, colon), StandardCharsets.UTF_8);
|
||||
String password = URLDecoder.decode(userInfo.substring(colon + 1), StandardCharsets.UTF_8);
|
||||
String path = uri.getPath();
|
||||
if (uri.getHost() == null || path == null || path.length() < 2) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int port = uri.getPort() < 0 ? 5432 : uri.getPort();
|
||||
String url = "jdbc:postgresql://" + uri.getHost() + ":" + port + path
|
||||
+ "?user=" + URLEncoder.encode(user, StandardCharsets.UTF_8)
|
||||
+ "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8);
|
||||
return new Jdbc(withTimeouts(url), user, password);
|
||||
} catch (RuntimeException e) {
|
||||
fail("DATABASE_URL");
|
||||
return new Jdbc("", "", "");
|
||||
}
|
||||
}
|
||||
|
||||
private static Jdbc fromJdbc(String url) {
|
||||
String user = query(url, "user");
|
||||
String password = query(url, "password");
|
||||
if (user == null || password == null) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
return new Jdbc(withTimeouts(url), user, password);
|
||||
}
|
||||
|
||||
private static String query(String url, String name) {
|
||||
int question = url.indexOf('?');
|
||||
if (question < 0) {
|
||||
return null;
|
||||
}
|
||||
for (String part : url.substring(question + 1).split("&")) {
|
||||
int eq = part.indexOf('=');
|
||||
if (eq < 0) {
|
||||
continue;
|
||||
}
|
||||
if (part.substring(0, eq).equals(name)) {
|
||||
return URLDecoder.decode(part.substring(eq + 1), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String withTimeouts(String url) {
|
||||
if (url.contains("socketTimeout=")) {
|
||||
return url;
|
||||
}
|
||||
String extra = "connectTimeout=2&socketTimeout=2";
|
||||
return url + (url.contains("?") ? "&" : "?") + extra;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
public final class Main {
|
||||
private Main() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Config config = Config.fromEnvironment();
|
||||
MessengerServer server;
|
||||
try {
|
||||
server = MessengerServer.start(config, System.out::println, System.err::println);
|
||||
} catch (Exception e) {
|
||||
System.err.println("event=startup_failed type=" + e.getClass().getSimpleName());
|
||||
System.exit(1);
|
||||
return;
|
||||
}
|
||||
System.out.println("event=listen host=" + config.host
|
||||
+ " port=" + server.port()
|
||||
+ " env=" + config.appEnv
|
||||
+ " session_store=redis"
|
||||
+ " session_ttl_seconds=" + config.sessionTtlSeconds);
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
long started = System.nanoTime();
|
||||
System.out.println("event=shutdown phase=begin");
|
||||
server.stop();
|
||||
long durationMs = (System.nanoTime() - started) / 1_000_000L;
|
||||
System.out.println("event=shutdown phase=end duration_ms=" + durationMs);
|
||||
}, "shutdown"));
|
||||
try {
|
||||
Thread.currentThread().join();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.StreamReadFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
final class MessengerServer {
|
||||
static final String BASIC = "Basic realm=\"messenger\", charset=\"UTF-8\"";
|
||||
static final String BEARER = "Bearer realm=\"messenger\"";
|
||||
|
||||
private static final int MAX_BODY = 64 * 1024;
|
||||
private static final Pattern USERNAME = Pattern.compile("^[a-z0-9_]{3,32}$");
|
||||
private static final Pattern UUID_TEXT = Pattern.compile(
|
||||
"(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
|
||||
private static final JsonMapper JSON = JsonMapper.builder()
|
||||
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
|
||||
.build();
|
||||
|
||||
private final HttpServer http;
|
||||
private final PostgresStore store;
|
||||
private final SessionStore sessions;
|
||||
private final Passwords passwords;
|
||||
private final int sessionTtlSeconds;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final AtomicBoolean accepting = new AtomicBoolean(true);
|
||||
private final AtomicBoolean stopped = new AtomicBoolean(false);
|
||||
private final Consumer<String> info;
|
||||
private final Consumer<String> error;
|
||||
private final int port;
|
||||
|
||||
private MessengerServer(Config config, Consumer<String> info, Consumer<String> error) throws IOException {
|
||||
this.info = info;
|
||||
this.error = error;
|
||||
this.sessionTtlSeconds = config.sessionTtlSeconds;
|
||||
this.passwords = new Passwords(config.bcryptCost);
|
||||
this.store = new PostgresStore(config.jdbcUrl, config.dbUser, config.dbPassword, passwords);
|
||||
this.sessions = new SessionStore(config.redisUrl);
|
||||
this.store.migrate();
|
||||
this.http = HttpServer.create(new InetSocketAddress(config.host, config.port), 128);
|
||||
this.port = http.getAddress().getPort();
|
||||
ExecutorService pool = Executors.newFixedThreadPool(64, runnable -> {
|
||||
Thread thread = new Thread(runnable, "http");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
http.setExecutor(pool);
|
||||
http.createContext("/", this::handle);
|
||||
http.start();
|
||||
}
|
||||
|
||||
static MessengerServer start(Config config, Consumer<String> info, Consumer<String> error) throws IOException {
|
||||
return new MessengerServer(config, info, error);
|
||||
}
|
||||
|
||||
int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
PostgresStore store() {
|
||||
return store;
|
||||
}
|
||||
|
||||
void refuseNewRequests() {
|
||||
accepting.set(false);
|
||||
}
|
||||
|
||||
void stop() {
|
||||
accepting.set(false);
|
||||
if (stopped.compareAndSet(false, true)) {
|
||||
http.stop(2);
|
||||
sessions.close();
|
||||
store.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) {
|
||||
long started = System.nanoTime();
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String method = exchange.getRequestMethod();
|
||||
String path = exchange.getRequestURI().getPath() == null ? "" : exchange.getRequestURI().getPath();
|
||||
int status = 500;
|
||||
try {
|
||||
status = dispatch(exchange, requestId, method, path);
|
||||
} catch (ApiException exception) {
|
||||
status = writeError(exchange, requestId, exception);
|
||||
} catch (Exception exception) {
|
||||
error.accept("event=unexpected type=" + exception.getClass().getName());
|
||||
status = writeError(exchange, requestId, ApiException.internalError());
|
||||
} finally {
|
||||
long durationMs = (System.nanoTime() - started) / 1_000_000L;
|
||||
info.accept("request_id=" + requestId
|
||||
+ " method=" + method
|
||||
+ " path=" + path
|
||||
+ " status=" + status
|
||||
+ " duration_ms=" + durationMs);
|
||||
exchange.close();
|
||||
}
|
||||
}
|
||||
|
||||
private int dispatch(HttpExchange exchange, String requestId, String method, String path) throws IOException {
|
||||
if (!accepting.get()) {
|
||||
if ("GET".equals(method) && "/health/live".equals(path)) {
|
||||
return writeJson(exchange, requestId, 200, health());
|
||||
}
|
||||
throw ApiException.shuttingDown();
|
||||
}
|
||||
if ("GET".equals(method) && "/health/live".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
return writeJson(exchange, requestId, 200, health());
|
||||
}
|
||||
if ("GET".equals(method) && "/health/ready".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
if (!store.ready() || !sessions.ready()) {
|
||||
throw ApiException.dependency();
|
||||
}
|
||||
return writeJson(exchange, requestId, 200, health());
|
||||
}
|
||||
if ("POST".equals(method) && "/api/v1/users".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
JsonNode body = readObject(readBody(exchange));
|
||||
allowOnly(body, "username", "display_name", "password");
|
||||
String username = requiredText(body, "username");
|
||||
if (!USERNAME.matcher(username).matches()) {
|
||||
throw ApiException.invalid("Недопустимый username");
|
||||
}
|
||||
String displayName = requiredText(body, "display_name");
|
||||
requireCodePoints(displayName, 1, 100, "display_name");
|
||||
String password = requiredText(body, "password");
|
||||
int passwordPoints = password.codePointCount(0, password.length());
|
||||
if (passwordPoints < 12 || passwordPoints > 128) {
|
||||
throw ApiException.invalid("Недопустимый пароль");
|
||||
}
|
||||
User user = store.createUser(username, displayName, password);
|
||||
return writeJson(exchange, requestId, 201, userJson(user));
|
||||
}
|
||||
if ("POST".equals(method) && "/api/v1/auth/sessions".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
if (readLimited(exchange.getRequestBody()).length > 0) {
|
||||
throw ApiException.invalid("Тело запроса не допускается");
|
||||
}
|
||||
Credentials credentials = basic(exchange);
|
||||
User user;
|
||||
try {
|
||||
user = store.authenticate(credentials.username, credentials.password);
|
||||
} catch (ApiException exception) {
|
||||
if (exception.status == 401) {
|
||||
throw ApiException.unauthorized(BASIC);
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
String token = newToken();
|
||||
sessions.save(token, user.id(), sessionTtlSeconds);
|
||||
Instant expires = Instant.now().plusSeconds(sessionTtlSeconds).truncatedTo(ChronoUnit.SECONDS);
|
||||
ObjectNode session = JSON.createObjectNode();
|
||||
session.put("token", token);
|
||||
session.put("token_type", "Bearer");
|
||||
session.put("expires_at", DateTimeFormatter.ISO_INSTANT.format(expires));
|
||||
session.set("user", userJson(user));
|
||||
return writeJson(exchange, requestId, 201, session);
|
||||
}
|
||||
if ("DELETE".equals(method) && "/api/v1/auth/sessions/current".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
String token = bearer(exchange);
|
||||
if (!sessions.revoke(token)) {
|
||||
throw ApiException.unauthorized(BEARER);
|
||||
}
|
||||
return writeEmpty(exchange, requestId);
|
||||
}
|
||||
|
||||
if ("GET".equals(method) && "/api/v1/users/me".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
User user = requireUser(exchange);
|
||||
return writeJson(exchange, requestId, 200, userJson(user));
|
||||
}
|
||||
if ("POST".equals(method) && "/api/v1/chats".equals(path)) {
|
||||
rejectQuery(exchange);
|
||||
User user = requireUser(exchange);
|
||||
JsonNode body = readObject(readBody(exchange));
|
||||
allowOnly(body, "title", "member_ids");
|
||||
String title = requiredText(body, "title");
|
||||
requireCodePoints(title, 1, 100, "title");
|
||||
List<UUID> members = memberIds(body);
|
||||
Chat chat = store.createChat(user.id(), title, members);
|
||||
return writeJson(exchange, requestId, 201, chatJson(chat));
|
||||
}
|
||||
if ("GET".equals(method) && "/api/v1/chats".equals(path)) {
|
||||
User user = requireUser(exchange);
|
||||
Query query = pagingQuery(exchange);
|
||||
int limit = query.limit == null ? 50 : query.limit;
|
||||
Position position = query.cursor == null ? null : decodeCursor(query.cursor, "c", user.id());
|
||||
List<Chat> chats = store.chats(
|
||||
user.id(),
|
||||
limit + 1,
|
||||
position == null ? null : position.createdAt,
|
||||
position == null ? null : position.id);
|
||||
return writeSlice(exchange, requestId, chats, limit, "c", user.id(), Chat::createdAt, Chat::id, MessengerServer::chatJson);
|
||||
}
|
||||
|
||||
ChatRoute chatRoute = matchChat(path);
|
||||
if (chatRoute != null && "GET".equals(method) && chatRoute.messages) {
|
||||
User user = requireUser(exchange);
|
||||
UUID chatId = parsePathUuid(chatRoute.idText);
|
||||
Query query = pagingQuery(exchange);
|
||||
int limit = query.limit == null ? 50 : query.limit;
|
||||
if (store.visibleChat(user.id(), chatId).isEmpty()) {
|
||||
throw ApiException.notFound();
|
||||
}
|
||||
Position position = query.cursor == null ? null : decodeCursor(query.cursor, "m", chatId);
|
||||
List<Message> messages = store.messages(
|
||||
user.id(),
|
||||
chatId,
|
||||
limit + 1,
|
||||
position == null ? null : position.createdAt,
|
||||
position == null ? null : position.id);
|
||||
return writeSlice(exchange, requestId, messages, limit, "m", chatId, Message::createdAt, Message::id, MessengerServer::messageJson);
|
||||
}
|
||||
if (chatRoute != null && "POST".equals(method) && chatRoute.messages) {
|
||||
rejectQuery(exchange);
|
||||
User user = requireUser(exchange);
|
||||
UUID chatId = parsePathUuid(chatRoute.idText);
|
||||
JsonNode body = readObject(readBody(exchange));
|
||||
allowOnly(body, "text");
|
||||
String text = requiredText(body, "text");
|
||||
requireCodePoints(text, 1, 4000, "text");
|
||||
Message message = store.addMessage(user.id(), chatId, text);
|
||||
return writeJson(exchange, requestId, 201, messageJson(message));
|
||||
}
|
||||
if (chatRoute != null && "GET".equals(method)) {
|
||||
rejectQuery(exchange);
|
||||
User user = requireUser(exchange);
|
||||
UUID chatId = parsePathUuid(chatRoute.idText);
|
||||
Chat chat = store.visibleChat(user.id(), chatId).orElseThrow(ApiException::notFound);
|
||||
return writeJson(exchange, requestId, 200, chatJson(chat));
|
||||
}
|
||||
throw ApiException.notFound();
|
||||
}
|
||||
|
||||
private User requireUser(HttpExchange exchange) {
|
||||
String token = bearer(exchange);
|
||||
UUID userId = sessions.find(token).orElseThrow(() -> ApiException.unauthorized(BEARER));
|
||||
return store.findUser(userId).orElseThrow(() -> ApiException.unauthorized(BEARER));
|
||||
}
|
||||
|
||||
private String bearer(HttpExchange exchange) {
|
||||
String header = singleHeader(exchange, "Authorization");
|
||||
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
|
||||
throw ApiException.unauthorized(BEARER);
|
||||
}
|
||||
String token = header.substring(7);
|
||||
if (token.isBlank() || token.indexOf(' ') >= 0) {
|
||||
throw ApiException.unauthorized(BEARER);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
private Credentials basic(HttpExchange exchange) {
|
||||
String header = singleHeader(exchange, "Authorization");
|
||||
if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) {
|
||||
throw ApiException.unauthorized(BASIC);
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(header.substring(6).trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiException.unauthorized(BASIC);
|
||||
}
|
||||
String pair = new String(decoded, StandardCharsets.UTF_8);
|
||||
int colon = pair.indexOf(':');
|
||||
if (colon <= 0 || colon == pair.length() - 1) {
|
||||
throw ApiException.unauthorized(BASIC);
|
||||
}
|
||||
return new Credentials(pair.substring(0, colon), pair.substring(colon + 1));
|
||||
}
|
||||
|
||||
private static String singleHeader(HttpExchange exchange, String name) {
|
||||
List<String> headers = exchange.getRequestHeaders().get(name);
|
||||
if (headers == null || headers.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
return headers.get(0);
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static UUID parsePathUuid(String raw) {
|
||||
if (!UUID_TEXT.matcher(raw).matches()) {
|
||||
throw ApiException.invalid("Некорректный идентификатор");
|
||||
}
|
||||
return UUID.fromString(raw);
|
||||
}
|
||||
|
||||
private static ChatRoute matchChat(String path) {
|
||||
String prefix = "/api/v1/chats/";
|
||||
if (!path.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
String rest = path.substring(prefix.length());
|
||||
if (rest.isEmpty() || rest.charAt(0) == '/') {
|
||||
return null;
|
||||
}
|
||||
int slash = rest.indexOf('/');
|
||||
if (slash < 0) {
|
||||
return new ChatRoute(rest, false);
|
||||
}
|
||||
if (rest.substring(slash).equals("/messages")) {
|
||||
return new ChatRoute(rest.substring(0, slash), true);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] readBody(HttpExchange exchange) throws IOException {
|
||||
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (contentType == null) {
|
||||
throw ApiException.invalid("Ожидался Content-Type application/json");
|
||||
}
|
||||
String mime = contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
|
||||
if (!mime.equals("application/json")) {
|
||||
throw ApiException.invalid("Ожидался Content-Type application/json");
|
||||
}
|
||||
return readLimited(exchange.getRequestBody());
|
||||
}
|
||||
|
||||
private static byte[] readLimited(InputStream input) throws IOException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[4096];
|
||||
int total = 0;
|
||||
int read;
|
||||
while ((read = input.read(buffer)) >= 0) {
|
||||
total += read;
|
||||
if (total > MAX_BODY) {
|
||||
throw ApiException.tooLarge();
|
||||
}
|
||||
output.write(buffer, 0, read);
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
|
||||
private static JsonNode readObject(byte[] bytes) {
|
||||
if (bytes.length == 0) {
|
||||
throw ApiException.invalid("Пустое тело запроса");
|
||||
}
|
||||
try (JsonParser parser = JSON.createParser(bytes)) {
|
||||
JsonNode node = JSON.readTree(parser);
|
||||
if (parser.nextToken() != null) {
|
||||
throw ApiException.invalid("Некорректный JSON");
|
||||
}
|
||||
if (node == null || !node.isObject()) {
|
||||
throw ApiException.invalid("Ожидался JSON-объект");
|
||||
}
|
||||
return node;
|
||||
} catch (ApiException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
throw ApiException.invalid("Некорректный JSON");
|
||||
}
|
||||
}
|
||||
|
||||
private static void allowOnly(JsonNode object, String... fields) {
|
||||
Set<String> allowed = Set.of(fields);
|
||||
object.fieldNames().forEachRemaining(name -> {
|
||||
if (!allowed.contains(name)) {
|
||||
throw ApiException.invalid("В запросе есть лишние поля");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static String requiredText(JsonNode object, String field) {
|
||||
if (!object.has(field) || object.get(field).isNull()) {
|
||||
throw ApiException.invalid("Отсутствует поле " + field);
|
||||
}
|
||||
JsonNode node = object.get(field);
|
||||
if (!node.isTextual()) {
|
||||
throw ApiException.invalid("Поле " + field + " должно быть строкой");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
private static void requireCodePoints(String value, int min, int max, String field) {
|
||||
int count = value.codePointCount(0, value.length());
|
||||
if (count < min || count > max || isBlank(value)) {
|
||||
throw ApiException.invalid("Недопустимое значение " + field);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value.codePoints().allMatch(cp -> Character.isWhitespace(cp) || Character.isSpaceChar(cp));
|
||||
}
|
||||
|
||||
private static List<UUID> memberIds(JsonNode object) {
|
||||
if (!object.has("member_ids") || !object.get("member_ids").isArray()) {
|
||||
throw ApiException.invalid("Поле member_ids должно быть массивом");
|
||||
}
|
||||
ArrayNode array = (ArrayNode) object.get("member_ids");
|
||||
if (array.size() < 1 || array.size() > 100) {
|
||||
throw ApiException.invalid("Недопустимое число участников");
|
||||
}
|
||||
List<UUID> ids = new ArrayList<>();
|
||||
for (JsonNode item : array) {
|
||||
if (!item.isTextual() || !UUID_TEXT.matcher(item.textValue()).matches()) {
|
||||
throw ApiException.invalid("Некорректный идентификатор участника");
|
||||
}
|
||||
UUID id = UUID.fromString(item.textValue());
|
||||
if (ids.contains(id)) {
|
||||
throw ApiException.invalid("Повторяющийся участник");
|
||||
}
|
||||
ids.add(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static void rejectQuery(HttpExchange exchange) {
|
||||
String raw = exchange.getRequestURI().getRawQuery();
|
||||
if (raw != null && !raw.isEmpty()) {
|
||||
throw ApiException.invalid("Неподдерживаемые параметры запроса");
|
||||
}
|
||||
}
|
||||
|
||||
private static Query pagingQuery(HttpExchange exchange) {
|
||||
String raw = exchange.getRequestURI().getRawQuery();
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return new Query(null, null);
|
||||
}
|
||||
java.util.Map<String, List<String>> params = new java.util.LinkedHashMap<>();
|
||||
for (String part : raw.split("&", -1)) {
|
||||
if (part.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
int eq = part.indexOf('=');
|
||||
String key = decode(eq < 0 ? part : part.substring(0, eq));
|
||||
String value = decode(eq < 0 ? "" : part.substring(eq + 1));
|
||||
params.computeIfAbsent(key, ignored -> new ArrayList<>()).add(value);
|
||||
}
|
||||
for (String key : params.keySet()) {
|
||||
if (!key.equals("limit") && !key.equals("cursor")) {
|
||||
throw ApiException.invalid("Неподдерживаемый параметр запроса");
|
||||
}
|
||||
}
|
||||
Integer limit = null;
|
||||
if (params.containsKey("limit")) {
|
||||
List<String> values = params.get("limit");
|
||||
if (values.size() != 1 || !values.get(0).matches("[0-9]{1,3}")) {
|
||||
throw ApiException.invalid("Некорректный limit");
|
||||
}
|
||||
int parsed = Integer.parseInt(values.get(0));
|
||||
if (parsed < 1 || parsed > 100) {
|
||||
throw ApiException.invalid("Некорректный limit");
|
||||
}
|
||||
limit = parsed;
|
||||
}
|
||||
String cursor = null;
|
||||
if (params.containsKey("cursor")) {
|
||||
List<String> values = params.get("cursor");
|
||||
if (values.size() != 1 || values.get(0).isEmpty()) {
|
||||
throw ApiException.invalid("Некорректный cursor");
|
||||
}
|
||||
cursor = values.get(0);
|
||||
}
|
||||
return new Query(limit, cursor);
|
||||
}
|
||||
|
||||
private static String decode(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw ApiException.invalid("Некорректная строка запроса");
|
||||
}
|
||||
}
|
||||
|
||||
private <T> int writeSlice(
|
||||
HttpExchange exchange,
|
||||
String requestId,
|
||||
List<T> loaded,
|
||||
int limit,
|
||||
String kind,
|
||||
UUID scope,
|
||||
java.util.function.Function<T, Instant> createdAt,
|
||||
java.util.function.Function<T, UUID> id,
|
||||
java.util.function.Function<T, ObjectNode> json) throws IOException {
|
||||
boolean more = loaded.size() > limit;
|
||||
int end = more ? limit : loaded.size();
|
||||
ObjectNode page = JSON.createObjectNode();
|
||||
ArrayNode items = page.putArray("items");
|
||||
for (int i = 0; i < end; i++) {
|
||||
items.add(json.apply(loaded.get(i)));
|
||||
}
|
||||
if (more && end > 0) {
|
||||
T last = loaded.get(end - 1);
|
||||
page.put("next_cursor", encodeCursor(kind, scope, createdAt.apply(last), id.apply(last)));
|
||||
} else {
|
||||
page.putNull("next_cursor");
|
||||
}
|
||||
return writeJson(exchange, requestId, 200, page);
|
||||
}
|
||||
|
||||
private static String encodeCursor(String kind, UUID scope, Instant createdAt, UUID id) {
|
||||
String raw = kind + "|" + scope + "|" + createdAt.toEpochMilli() + "|" + id;
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static Position decodeCursor(String cursor, String kind, UUID scope) {
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getUrlDecoder().decode(pad(cursor));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw ApiException.invalid("Некорректный cursor");
|
||||
}
|
||||
String raw = new String(decoded, StandardCharsets.UTF_8);
|
||||
String[] parts = raw.split("\\|", -1);
|
||||
if (parts.length != 4) {
|
||||
throw ApiException.invalid("Некорректный cursor");
|
||||
}
|
||||
if (!parts[0].equals(kind)) {
|
||||
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
||||
}
|
||||
UUID cursorScope;
|
||||
long millis;
|
||||
UUID id;
|
||||
try {
|
||||
cursorScope = UUID.fromString(parts[1]);
|
||||
millis = Long.parseLong(parts[2]);
|
||||
id = UUID.fromString(parts[3]);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw ApiException.invalid("Некорректный cursor");
|
||||
}
|
||||
if (!cursorScope.equals(scope)) {
|
||||
throw ApiException.invalid("Cursor относится к другому ресурсу");
|
||||
}
|
||||
return new Position(Instant.ofEpochMilli(millis), id);
|
||||
}
|
||||
|
||||
private static String pad(String value) {
|
||||
int mod = value.length() % 4;
|
||||
if (mod == 0) {
|
||||
return value;
|
||||
}
|
||||
return value + "====".substring(mod);
|
||||
}
|
||||
|
||||
private static ObjectNode health() {
|
||||
return JSON.createObjectNode().put("status", "ok");
|
||||
}
|
||||
|
||||
private static ObjectNode userJson(User user) {
|
||||
ObjectNode node = JSON.createObjectNode();
|
||||
node.put("id", user.id().toString());
|
||||
node.put("username", user.username());
|
||||
node.put("display_name", user.displayName());
|
||||
node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(user.createdAt()));
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ObjectNode chatJson(Chat chat) {
|
||||
ObjectNode node = JSON.createObjectNode();
|
||||
node.put("id", chat.id().toString());
|
||||
node.put("title", chat.title());
|
||||
ArrayNode members = node.putArray("member_ids");
|
||||
for (UUID memberId : chat.memberIds()) {
|
||||
members.add(memberId.toString());
|
||||
}
|
||||
node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(chat.createdAt()));
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ObjectNode messageJson(Message message) {
|
||||
ObjectNode node = JSON.createObjectNode();
|
||||
node.put("id", message.id().toString());
|
||||
node.put("chat_id", message.chatId().toString());
|
||||
node.put("sender_id", message.senderId().toString());
|
||||
node.put("text", message.text());
|
||||
node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(message.createdAt()));
|
||||
return node;
|
||||
}
|
||||
|
||||
private int writeJson(HttpExchange exchange, String requestId, int status, JsonNode body) throws IOException {
|
||||
byte[] bytes = JSON.writeValueAsBytes(body);
|
||||
return writeBytes(exchange, requestId, status, bytes, null);
|
||||
}
|
||||
|
||||
private int writeEmpty(HttpExchange exchange, String requestId) throws IOException {
|
||||
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
return 204;
|
||||
}
|
||||
|
||||
private int writeError(HttpExchange exchange, String requestId, ApiException exception) {
|
||||
ObjectNode body = JSON.createObjectNode();
|
||||
ObjectNode errorNode = body.putObject("error");
|
||||
errorNode.put("code", exception.code);
|
||||
errorNode.put("message", exception.clientMessage);
|
||||
errorNode.put("request_id", requestId);
|
||||
try {
|
||||
byte[] bytes = JSON.writeValueAsBytes(body);
|
||||
return writeBytes(exchange, requestId, exception.status, bytes, exception.challenge);
|
||||
} catch (IOException ioException) {
|
||||
error.accept("event=write_failed type=" + ioException.getClass().getName());
|
||||
return exception.status;
|
||||
}
|
||||
}
|
||||
|
||||
private int writeBytes(HttpExchange exchange, String requestId, int status, byte[] body, String challenge) throws IOException {
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
exchange.getResponseHeaders().set("X-Request-Id", requestId);
|
||||
if (challenge != null) {
|
||||
exchange.getResponseHeaders().set("WWW-Authenticate", challenge);
|
||||
}
|
||||
exchange.sendResponseHeaders(status, body.length);
|
||||
try (OutputStream output = exchange.getResponseBody()) {
|
||||
output.write(body);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
private record Query(Integer limit, String cursor) {
|
||||
}
|
||||
|
||||
private record Position(Instant createdAt, UUID id) {
|
||||
}
|
||||
|
||||
private record ChatRoute(String idText, boolean messages) {
|
||||
}
|
||||
|
||||
private record Credentials(String username, String password) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
record User(UUID id, String username, String displayName, Instant createdAt) {
|
||||
}
|
||||
|
||||
record Chat(UUID id, String title, List<UUID> memberIds, Instant createdAt) {
|
||||
}
|
||||
|
||||
record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import at.favre.lib.crypto.bcrypt.BCrypt;
|
||||
import at.favre.lib.crypto.bcrypt.LongPasswordStrategies;
|
||||
import at.favre.lib.crypto.bcrypt.LongPasswordStrategy;
|
||||
|
||||
/**
|
||||
* bcrypt сам по себе обрезает пароль на 72 байтах.
|
||||
* Перед ним пароль целиком проходит через SHA-512, поэтому длинный UTF-8 не теряется.
|
||||
* Наружу уходит только строка bcrypt, не сам пароль.
|
||||
*/
|
||||
final class Passwords {
|
||||
private final int cost;
|
||||
private final BCrypt.Hasher hasher;
|
||||
private final BCrypt.Verifyer verifyer;
|
||||
private final String dummyHash;
|
||||
|
||||
Passwords(int cost) {
|
||||
if (cost < 4 || cost > 14) {
|
||||
throw new IllegalArgumentException("bcrypt cost");
|
||||
}
|
||||
this.cost = cost;
|
||||
LongPasswordStrategy strategy = LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A);
|
||||
this.hasher = BCrypt.with(BCrypt.Version.VERSION_2A, strategy);
|
||||
this.verifyer = BCrypt.verifyer(BCrypt.Version.VERSION_2A, strategy);
|
||||
this.dummyHash = hasher.hashToString(cost, "missing-user-timing".toCharArray());
|
||||
}
|
||||
|
||||
String hash(String password) {
|
||||
return hasher.hashToString(cost, password.toCharArray());
|
||||
}
|
||||
|
||||
boolean verify(String password, String hash) {
|
||||
return verifyer.verify(password.toCharArray(), hash).verified;
|
||||
}
|
||||
|
||||
void burnMissing(String password) {
|
||||
verifyer.verify(password.toCharArray(), dummyHash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Пользователи, чаты, участники и сообщения лежат в PostgreSQL.
|
||||
* Создание чата и запись сообщения идут одной транзакцией вместе с монотонными часами.
|
||||
* Пул ограничен, у соединения короткий таймаут: если БД недоступна, запрос заканчивается 503.
|
||||
*/
|
||||
final class PostgresStore implements AutoCloseable {
|
||||
private final HikariDataSource dataSource;
|
||||
private final Passwords passwords;
|
||||
|
||||
PostgresStore(String jdbcUrl, String username, String password, Passwords passwords) {
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setJdbcUrl(jdbcUrl);
|
||||
config.setUsername(username);
|
||||
config.setPassword(password);
|
||||
config.setMaximumPoolSize(10);
|
||||
config.setMinimumIdle(1);
|
||||
config.setConnectionTimeout(2000);
|
||||
config.setValidationTimeout(1000);
|
||||
config.setInitializationFailTimeout(10000);
|
||||
config.setConnectionInitSql("SET TIME ZONE 'UTC'");
|
||||
this.dataSource = new HikariDataSource(config);
|
||||
this.passwords = passwords;
|
||||
}
|
||||
|
||||
void migrate() {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
conn.setAutoCommit(false);
|
||||
try (Statement statement = conn.createStatement()) {
|
||||
statement.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
""");
|
||||
}
|
||||
if (!applied(conn, "V1")) {
|
||||
runScript(conn, "/db/migration/V1__schema.sql");
|
||||
try (PreparedStatement insert = conn.prepareStatement(
|
||||
"INSERT INTO schema_migrations (version) VALUES (?)")) {
|
||||
insert.setString(1, "V1");
|
||||
insert.executeUpdate();
|
||||
}
|
||||
}
|
||||
conn.commit();
|
||||
} catch (SQLException | IOException e) {
|
||||
throw new IllegalStateException("migration failed");
|
||||
}
|
||||
}
|
||||
|
||||
User createUser(String username, String displayName, String password) {
|
||||
String hash = passwords.hash(password);
|
||||
Connection conn = open();
|
||||
try {
|
||||
conn.setAutoCommit(false);
|
||||
long millis = tick(conn);
|
||||
UUID id = UUID.randomUUID();
|
||||
try (PreparedStatement insert = conn.prepareStatement("""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""")) {
|
||||
insert.setObject(1, id);
|
||||
insert.setString(2, username);
|
||||
insert.setString(3, displayName);
|
||||
insert.setString(4, hash);
|
||||
insert.setObject(5, timestamp(millis));
|
||||
insert.executeUpdate();
|
||||
}
|
||||
User user = loadUser(conn, id).orElseThrow(ApiException::internalError);
|
||||
conn.commit();
|
||||
return user;
|
||||
} catch (ApiException e) {
|
||||
rollback(conn);
|
||||
throw e;
|
||||
} catch (SQLException e) {
|
||||
rollback(conn);
|
||||
if ("23505".equals(e.getSQLState())) {
|
||||
throw ApiException.conflict();
|
||||
}
|
||||
throw map(e);
|
||||
} finally {
|
||||
close(conn);
|
||||
}
|
||||
}
|
||||
|
||||
User authenticate(String username, String password) {
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
""")) {
|
||||
statement.setString(1, username);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
passwords.burnMissing(password);
|
||||
throw ApiException.unauthorized(null);
|
||||
}
|
||||
String hash = rows.getString("password_hash");
|
||||
if (!passwords.verify(password, hash)) {
|
||||
throw ApiException.unauthorized(null);
|
||||
}
|
||||
return userFrom(rows);
|
||||
}
|
||||
} catch (ApiException e) {
|
||||
throw e;
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
Optional<User> findUser(UUID id) {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
return loadUser(conn, id);
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
Chat createChat(UUID callerId, String title, List<UUID> memberIds) {
|
||||
if (!memberIds.contains(callerId)) {
|
||||
throw ApiException.invalid("Создатель чата должен входить в список участников");
|
||||
}
|
||||
Connection conn = open();
|
||||
try {
|
||||
conn.setAutoCommit(false);
|
||||
List<UUID> locked = new ArrayList<>(memberIds);
|
||||
locked.sort(UUID::compareTo);
|
||||
for (UUID memberId : locked) {
|
||||
if (!lockUser(conn, memberId)) {
|
||||
throw ApiException.invalid("Указан неизвестный участник");
|
||||
}
|
||||
}
|
||||
long millis = tick(conn);
|
||||
UUID chatId = UUID.randomUUID();
|
||||
try (PreparedStatement insert = conn.prepareStatement("""
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES (?, ?, ?)
|
||||
""")) {
|
||||
insert.setObject(1, chatId);
|
||||
insert.setString(2, title);
|
||||
insert.setObject(3, timestamp(millis));
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement member = conn.prepareStatement("""
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
VALUES (?, ?, ?)
|
||||
""")) {
|
||||
for (int i = 0; i < memberIds.size(); i++) {
|
||||
member.setObject(1, chatId);
|
||||
member.setObject(2, memberIds.get(i));
|
||||
member.setInt(3, i);
|
||||
member.addBatch();
|
||||
}
|
||||
member.executeBatch();
|
||||
}
|
||||
Chat chat = loadChat(conn, callerId, chatId).orElseThrow(ApiException::internalError);
|
||||
conn.commit();
|
||||
return chat;
|
||||
} catch (ApiException e) {
|
||||
rollback(conn);
|
||||
throw e;
|
||||
} catch (SQLException e) {
|
||||
rollback(conn);
|
||||
if ("23503".equals(e.getSQLState())) {
|
||||
throw ApiException.invalid("Указан неизвестный участник");
|
||||
}
|
||||
throw map(e);
|
||||
} finally {
|
||||
close(conn);
|
||||
}
|
||||
}
|
||||
|
||||
List<Chat> chats(UUID userId, int limit, Instant afterTime, UUID afterId) {
|
||||
String sql = """
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ?
|
||||
""";
|
||||
if (afterTime != null) {
|
||||
sql += " WHERE (c.created_at, c.id) > (?, ?)";
|
||||
}
|
||||
sql += " ORDER BY c.created_at, c.id LIMIT ?";
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||
int index = 1;
|
||||
statement.setObject(index++, userId);
|
||||
if (afterTime != null) {
|
||||
statement.setObject(index++, timestamp(afterTime));
|
||||
statement.setObject(index++, afterId);
|
||||
}
|
||||
statement.setInt(index, limit);
|
||||
List<Chat> chats = new ArrayList<>();
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
UUID id = rows.getObject("id", UUID.class);
|
||||
chats.add(new Chat(
|
||||
id,
|
||||
rows.getString("title"),
|
||||
members(conn, id),
|
||||
instant(rows, "created_at")));
|
||||
}
|
||||
}
|
||||
return chats;
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
Optional<Chat> visibleChat(UUID userId, UUID chatId) {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
return loadChat(conn, userId, chatId);
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
Message addMessage(UUID senderId, UUID chatId, String text) {
|
||||
Connection conn = open();
|
||||
try {
|
||||
conn.setAutoCommit(false);
|
||||
long millis = tick(conn);
|
||||
UUID id = UUID.randomUUID();
|
||||
try (PreparedStatement insert = conn.prepareStatement("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
||||
SELECT ?, ?, ?, ?, ?
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = ? AND user_id = ?
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, body, created_at
|
||||
""")) {
|
||||
insert.setObject(1, id);
|
||||
insert.setObject(2, chatId);
|
||||
insert.setObject(3, senderId);
|
||||
insert.setString(4, text);
|
||||
insert.setObject(5, timestamp(millis));
|
||||
insert.setObject(6, chatId);
|
||||
insert.setObject(7, senderId);
|
||||
try (ResultSet rows = insert.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
throw ApiException.notFound();
|
||||
}
|
||||
Message message = messageFrom(rows);
|
||||
conn.commit();
|
||||
return message;
|
||||
}
|
||||
}
|
||||
} catch (ApiException e) {
|
||||
rollback(conn);
|
||||
throw e;
|
||||
} catch (SQLException e) {
|
||||
rollback(conn);
|
||||
throw map(e);
|
||||
} finally {
|
||||
close(conn);
|
||||
}
|
||||
}
|
||||
|
||||
List<Message> messages(UUID userId, UUID chatId, int limit, Instant afterTime, UUID afterId) {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
if (loadChat(conn, userId, chatId).isEmpty()) {
|
||||
throw ApiException.notFound();
|
||||
}
|
||||
String sql = """
|
||||
SELECT id, chat_id, sender_id, body, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = ?
|
||||
""";
|
||||
if (afterTime != null) {
|
||||
sql += " AND (created_at, id) > (?, ?)";
|
||||
}
|
||||
sql += " ORDER BY created_at, id LIMIT ?";
|
||||
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||
int index = 1;
|
||||
statement.setObject(index++, chatId);
|
||||
if (afterTime != null) {
|
||||
statement.setObject(index++, timestamp(afterTime));
|
||||
statement.setObject(index++, afterId);
|
||||
}
|
||||
statement.setInt(index, limit);
|
||||
List<Message> messages = new ArrayList<>();
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
messages.add(messageFrom(rows));
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
} catch (ApiException e) {
|
||||
throw e;
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
String explainHistory(UUID chatId, Instant afterTime, UUID afterId) {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
try (Statement analyze = conn.createStatement()) {
|
||||
analyze.execute("ANALYZE messages");
|
||||
}
|
||||
try (PreparedStatement statement = conn.prepareStatement("""
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, body, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = ?
|
||||
AND (created_at, id) > (?, ?)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 50
|
||||
""")) {
|
||||
statement.setObject(1, chatId);
|
||||
statement.setObject(2, timestamp(afterTime));
|
||||
statement.setObject(3, afterId);
|
||||
StringBuilder plan = new StringBuilder();
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
plan.append(rows.getString(1)).append('\n');
|
||||
}
|
||||
}
|
||||
return plan.toString();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
boolean ready() {
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
Statement statement = conn.createStatement()) {
|
||||
statement.setQueryTimeout(2);
|
||||
statement.execute("SELECT 1");
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
dataSource.close();
|
||||
}
|
||||
|
||||
private boolean applied(Connection conn, String version) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = ?")) {
|
||||
statement.setString(1, version);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
return rows.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void runScript(Connection conn, String resource) throws SQLException, IOException {
|
||||
String sql;
|
||||
try (InputStream input = PostgresStore.class.getResourceAsStream(resource)) {
|
||||
if (input == null) {
|
||||
throw new IOException("missing migration");
|
||||
}
|
||||
sql = new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
StringBuilder current = new StringBuilder();
|
||||
for (String line : sql.split("\n", -1)) {
|
||||
if (line.trim().startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
current.append(line).append('\n');
|
||||
}
|
||||
for (String statement : current.toString().split(";")) {
|
||||
String trimmed = statement.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
try (Statement sqlStatement = conn.createStatement()) {
|
||||
sqlStatement.execute(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long tick(Connection conn) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement("""
|
||||
UPDATE app_clock
|
||||
SET millis = GREATEST(millis + 1, (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
|
||||
WHERE id = 1
|
||||
RETURNING millis
|
||||
""");
|
||||
ResultSet rows = statement.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
throw new SQLException("clock missing", "XX000");
|
||||
}
|
||||
return rows.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean lockUser(Connection conn, UUID id) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement(
|
||||
"SELECT id FROM users WHERE id = ? FOR UPDATE")) {
|
||||
statement.setObject(1, id);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
return rows.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<User> loadUser(Connection conn, UUID id) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = ?
|
||||
""")) {
|
||||
statement.setObject(1, id);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(userFrom(rows));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<Chat> loadChat(Connection conn, UUID userId, UUID chatId) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ?
|
||||
WHERE c.id = ?
|
||||
""")) {
|
||||
statement.setObject(1, userId);
|
||||
statement.setObject(2, chatId);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new Chat(
|
||||
rows.getObject("id", UUID.class),
|
||||
rows.getString("title"),
|
||||
members(conn, chatId),
|
||||
instant(rows, "created_at")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<UUID> members(Connection conn, UUID chatId) throws SQLException {
|
||||
try (PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ?
|
||||
ORDER BY position
|
||||
""")) {
|
||||
statement.setObject(1, chatId);
|
||||
List<UUID> ids = new ArrayList<>();
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
ids.add(rows.getObject("user_id", UUID.class));
|
||||
}
|
||||
}
|
||||
return List.copyOf(ids);
|
||||
}
|
||||
}
|
||||
|
||||
private static User userFrom(ResultSet rows) throws SQLException {
|
||||
return new User(
|
||||
rows.getObject("id", UUID.class),
|
||||
rows.getString("username"),
|
||||
rows.getString("display_name"),
|
||||
instant(rows, "created_at"));
|
||||
}
|
||||
|
||||
private static Message messageFrom(ResultSet rows) throws SQLException {
|
||||
return new Message(
|
||||
rows.getObject("id", UUID.class),
|
||||
rows.getObject("chat_id", UUID.class),
|
||||
rows.getObject("sender_id", UUID.class),
|
||||
rows.getString("body"),
|
||||
instant(rows, "created_at"));
|
||||
}
|
||||
|
||||
private static Instant instant(ResultSet rows, String column) throws SQLException {
|
||||
OffsetDateTime value = rows.getObject(column, OffsetDateTime.class);
|
||||
return Instant.ofEpochMilli(value.toInstant().toEpochMilli());
|
||||
}
|
||||
|
||||
private static OffsetDateTime timestamp(long millis) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
private static OffsetDateTime timestamp(Instant instant) {
|
||||
return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
private Connection open() {
|
||||
try {
|
||||
return dataSource.getConnection();
|
||||
} catch (SQLException e) {
|
||||
throw map(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rollback(Connection conn) {
|
||||
try {
|
||||
conn.rollback();
|
||||
} catch (SQLException ignored) {
|
||||
// соединение уже не годится, клиенту всё равно уйдёт ошибка
|
||||
}
|
||||
}
|
||||
|
||||
private static void close(Connection conn) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (SQLException ignored) {
|
||||
// пул сам выкинет сломанное соединение
|
||||
}
|
||||
}
|
||||
|
||||
private static ApiException map(SQLException e) {
|
||||
String state = e.getSQLState();
|
||||
if (state != null && (state.startsWith("08") || state.startsWith("53") || state.equals("57P01"))) {
|
||||
return ApiException.dependency();
|
||||
}
|
||||
String name = e.getClass().getName();
|
||||
if (name.contains("SQLTransientConnectionException") || name.contains("SQLTimeoutException")) {
|
||||
return ApiException.dependency();
|
||||
}
|
||||
System.err.println("event=sql state=" + (state == null ? "none" : state)
|
||||
+ " type=" + e.getClass().getSimpleName());
|
||||
return ApiException.internalError();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
|
||||
public final class ReadyProbe {
|
||||
private ReadyProbe() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String port = System.getenv().getOrDefault("APP_PORT", "8080");
|
||||
try {
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/health/ready"))
|
||||
.timeout(Duration.ofSeconds(2))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
|
||||
if (response.statusCode() != 200) {
|
||||
System.exit(1);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Сессии живут только в Redis. Ключ sess:<token> хранит id пользователя и снимается по TTL.
|
||||
* На стенде у Redis включён AOF, поэтому после рестарта контейнера ключи остаются на volume.
|
||||
*/
|
||||
final class SessionStore implements AutoCloseable {
|
||||
private final JedisPool pool;
|
||||
|
||||
SessionStore(String redisUrl) {
|
||||
JedisPoolConfig config = new JedisPoolConfig();
|
||||
config.setMaxTotal(16);
|
||||
config.setMaxWait(Duration.ofMillis(1000));
|
||||
config.setTestOnBorrow(true);
|
||||
this.pool = new JedisPool(config, URI.create(redisUrl), 1000);
|
||||
}
|
||||
|
||||
void save(String token, UUID userId, int ttlSeconds) {
|
||||
try (Jedis jedis = pool.getResource()) {
|
||||
jedis.setex(key(token), ttlSeconds, userId.toString());
|
||||
} catch (JedisException e) {
|
||||
throw ApiException.dependency();
|
||||
}
|
||||
}
|
||||
|
||||
Optional<UUID> find(String token) {
|
||||
try (Jedis jedis = pool.getResource()) {
|
||||
String value = jedis.get(key(token));
|
||||
if (value == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(UUID.fromString(value));
|
||||
} catch (JedisException | IllegalArgumentException e) {
|
||||
if (e instanceof IllegalArgumentException) {
|
||||
return Optional.empty();
|
||||
}
|
||||
throw ApiException.dependency();
|
||||
}
|
||||
}
|
||||
|
||||
boolean revoke(String token) {
|
||||
try (Jedis jedis = pool.getResource()) {
|
||||
return jedis.del(key(token)) == 1L;
|
||||
} catch (JedisException e) {
|
||||
throw ApiException.dependency();
|
||||
}
|
||||
}
|
||||
|
||||
boolean ready() {
|
||||
try (Jedis jedis = pool.getResource()) {
|
||||
return "PONG".equals(jedis.ping());
|
||||
} catch (JedisException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
pool.close();
|
||||
}
|
||||
|
||||
private static String key(String token) {
|
||||
return "sess:" + token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_key UNIQUE (username)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
body text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE app_clock (
|
||||
id integer PRIMARY KEY,
|
||||
millis bigint NOT NULL,
|
||||
CONSTRAINT app_clock_one CHECK (id = 1)
|
||||
);
|
||||
|
||||
INSERT INTO app_clock (id, millis) VALUES (1, 0);
|
||||
@@ -0,0 +1,581 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@Timeout(value = 4, unit = TimeUnit.MINUTES)
|
||||
class LabBehaviorTest {
|
||||
private static final JsonMapper JSON = new JsonMapper();
|
||||
private static final List<String> LOGS = new CopyOnWriteArrayList<>();
|
||||
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
|
||||
private static final String POSTGRES_NAME = "mtusi-lab2-test-pg";
|
||||
private static final String REDIS_NAME = "mtusi-lab2-test-redis";
|
||||
private static final String DB_USER = "messenger";
|
||||
private static final String DB_PASSWORD = "messenger";
|
||||
|
||||
private static MessengerServer server;
|
||||
private static String base;
|
||||
private static String jdbcUrl;
|
||||
private static int redisPort;
|
||||
|
||||
@BeforeAll
|
||||
static void start() throws Exception {
|
||||
docker("rm", "-f", POSTGRES_NAME);
|
||||
docker("rm", "-f", REDIS_NAME);
|
||||
docker("run", "-d", "--name", POSTGRES_NAME,
|
||||
"-e", "POSTGRES_USER=" + DB_USER,
|
||||
"-e", "POSTGRES_PASSWORD=" + DB_PASSWORD,
|
||||
"-e", "POSTGRES_DB=messenger",
|
||||
"-p", "127.0.0.1::5432",
|
||||
"postgres:16.6");
|
||||
docker("run", "-d", "--name", REDIS_NAME,
|
||||
"-p", "127.0.0.1::6379",
|
||||
"redis:7.4.2");
|
||||
waitUntil(POSTGRES_NAME, "pg_isready", "-U", DB_USER, "-d", "messenger");
|
||||
waitUntil(REDIS_NAME, "redis-cli", "ping");
|
||||
int pgPort = publishedPort(POSTGRES_NAME, 5432);
|
||||
redisPort = publishedPort(REDIS_NAME, 6379);
|
||||
jdbcUrl = "jdbc:postgresql://127.0.0.1:" + pgPort + "/messenger?connectTimeout=2&socketTimeout=2";
|
||||
String redisUrl = "redis://127.0.0.1:" + redisPort + "/0";
|
||||
Config config = new Config("127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 3600, 4);
|
||||
server = MessengerServer.start(config, LOGS::add, LOGS::add);
|
||||
base = "http://127.0.0.1:" + server.port();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stop() {
|
||||
if (server != null) {
|
||||
server.stop();
|
||||
}
|
||||
try {
|
||||
docker("rm", "-f", POSTGRES_NAME);
|
||||
docker("rm", "-f", REDIS_NAME);
|
||||
} catch (Exception ignored) {
|
||||
// контейнеры тестов уже сняты
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void migrationCanRunAgain() throws Exception {
|
||||
Passwords passwords = new Passwords(4);
|
||||
try (PostgresStore again = new PostgresStore(jdbcUrl, DB_USER, DB_PASSWORD, passwords)) {
|
||||
again.migrate();
|
||||
again.migrate();
|
||||
}
|
||||
assertEquals(1, queryInt("SELECT count(*) FROM schema_migrations"));
|
||||
assertEquals(1, queryInt("SELECT count(*) FROM app_clock"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void authValidationAndHistory() throws Exception {
|
||||
Resp live = call("GET", "/health/live", null, null);
|
||||
assertEquals(200, live.status);
|
||||
Resp ready = call("GET", "/health/ready", null, null);
|
||||
assertEquals(200, ready.status);
|
||||
|
||||
Resp broken = call("POST", "/api/v1/users", null, "{");
|
||||
assertEquals(400, broken.status);
|
||||
Resp typed = call("POST", "/api/v1/users", null, "{\"username\":1,\"display_name\":\"Аня\",\"password\":\"password-ok-12\"}");
|
||||
assertEquals(400, typed.status);
|
||||
Resp extra = call("POST", "/api/v1/users", null,
|
||||
"{\"username\":\"bad_extra_user\",\"display_name\":\"Аня\",\"password\":\"password-ok-12\",\"role\":\"x\"}");
|
||||
assertEquals(400, extra.status);
|
||||
Resp shortPassword = call("POST", "/api/v1/users", null,
|
||||
"{\"username\":\"short_pw_user\",\"display_name\":\"Аня\",\"password\":\"short\"}");
|
||||
assertEquals(400, shortPassword.status);
|
||||
Resp blankName = call("POST", "/api/v1/users", null,
|
||||
"{\"username\":\"blank_name_u\",\"display_name\":\" \",\"password\":\"password-ok-12\"}");
|
||||
assertEquals(400, blankName.status);
|
||||
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
JsonNode alice = register("alice_" + suffix, "Алиса");
|
||||
JsonNode bob = register("bob_" + suffix, "Боб 👋");
|
||||
JsonNode eve = register("eve_" + suffix, "Ева");
|
||||
assertFalse(alice.toString().contains("password"));
|
||||
Resp duplicate = call("POST", "/api/v1/users", null, userBody("alice_" + suffix, "Алиса"));
|
||||
assertEquals(409, duplicate.status);
|
||||
|
||||
Resp noAuth = call("GET", "/api/v1/users/me", null, null);
|
||||
assertEquals(401, noAuth.status);
|
||||
assertTrue(noAuth.challenge.toLowerCase().startsWith("bearer"));
|
||||
Resp byUserId = call("GET", "/api/v1/users/me", null, null, "X-User-Id", alice.get("id").asText());
|
||||
assertEquals(401, byUserId.status);
|
||||
|
||||
String aliceBasic = basic("alice_" + suffix, "password-ok-12");
|
||||
Resp wrong = call("POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
||||
basic("alice_" + suffix, "wrong-password-1"));
|
||||
assertEquals(401, wrong.status);
|
||||
assertTrue(wrong.challenge.toLowerCase().startsWith("basic"));
|
||||
Resp basicOnBusiness = call("GET", "/api/v1/users/me", null, null, "Authorization", aliceBasic);
|
||||
assertEquals(401, basicOnBusiness.status);
|
||||
assertTrue(basicOnBusiness.challenge.toLowerCase().startsWith("bearer"));
|
||||
|
||||
String aliceToken = login("alice_" + suffix);
|
||||
String bobToken = login("bob_" + suffix);
|
||||
String eveToken = login("eve_" + suffix);
|
||||
Resp me = call("GET", "/api/v1/users/me", aliceToken, null, "X-User-Id", eve.get("id").asText());
|
||||
assertEquals(200, me.status);
|
||||
assertEquals(alice.get("id").asText(), JSON.readTree(me.body).get("id").asText());
|
||||
|
||||
String chatBody = "{\"title\":\"Демо\",\"member_ids\":[\"" + alice.get("id").asText()
|
||||
+ "\",\"" + bob.get("id").asText() + "\"]}";
|
||||
Resp chat = call("POST", "/api/v1/chats", aliceToken, chatBody);
|
||||
assertEquals(201, chat.status);
|
||||
String chatId = JSON.readTree(chat.body).get("id").asText();
|
||||
Resp outsider = call("GET", "/api/v1/chats/" + chatId, eveToken, null);
|
||||
assertEquals(404, outsider.status);
|
||||
Resp hidden = call("GET", "/api/v1/chats?limit=100", eveToken, null);
|
||||
assertEquals(200, hidden.status);
|
||||
assertFalse(hidden.body.contains(chatId));
|
||||
|
||||
String secret = "synthetic-text-" + suffix;
|
||||
Resp empty = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"\"}");
|
||||
assertEquals(400, empty.status);
|
||||
Resp foreign = call("POST", "/api/v1/chats/" + chatId + "/messages", eveToken, "{\"text\":\"чужое\"}");
|
||||
assertEquals(404, foreign.status);
|
||||
Resp badLimit = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=0", aliceToken, null);
|
||||
assertEquals(400, badLimit.status);
|
||||
Resp first = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"" + secret + " 👋\"}");
|
||||
Resp second = call("POST", "/api/v1/chats/" + chatId + "/messages", bobToken, "{\"text\":\"ответ Боба\"}");
|
||||
assertEquals(201, first.status);
|
||||
assertEquals(201, second.status);
|
||||
Resp page1 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1", bobToken, null);
|
||||
JsonNode page1Json = JSON.readTree(page1.body);
|
||||
assertEquals(1, page1Json.get("items").size());
|
||||
assertFalse(page1Json.get("next_cursor").isNull());
|
||||
String cursor = page1Json.get("next_cursor").asText();
|
||||
Resp page2 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), aliceToken, null);
|
||||
JsonNode page2Json = JSON.readTree(page2.body);
|
||||
assertEquals(1, page2Json.get("items").size());
|
||||
assertTrue(page2Json.get("next_cursor").isNull());
|
||||
assertEquals(JSON.readTree(first.body).get("id").asText(), page1Json.get("items").get(0).get("id").asText());
|
||||
assertEquals(JSON.readTree(second.body).get("id").asText(), page2Json.get("items").get(0).get("id").asText());
|
||||
Resp stolen = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), eveToken, null);
|
||||
assertEquals(404, stolen.status);
|
||||
String joined = String.join("\n", LOGS);
|
||||
assertFalse(joined.contains(secret));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void parallelMessagesStayUnique() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
JsonNode user = register("par_" + suffix, "Параллель");
|
||||
String token = login("par_" + suffix);
|
||||
Resp chat = call("POST", "/api/v1/chats", token,
|
||||
"{\"title\":\"Гонка\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}");
|
||||
String chatId = JSON.readTree(chat.body).get("id").asText();
|
||||
ExecutorService pool = Executors.newFixedThreadPool(10);
|
||||
List<Future<Resp>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
int n = i;
|
||||
futures.add(pool.submit(() -> call("POST", "/api/v1/chats/" + chatId + "/messages", token,
|
||||
"{\"text\":\"m-" + n + "\"}")));
|
||||
}
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (Future<Resp> future : futures) {
|
||||
Resp response = future.get();
|
||||
assertEquals(201, response.status);
|
||||
ids.add(JSON.readTree(response.body).get("id").asText());
|
||||
}
|
||||
pool.shutdown();
|
||||
assertEquals(100, ids.stream().distinct().count());
|
||||
assertEquals(100, queryInt("SELECT count(*) FROM messages WHERE chat_id = '" + chatId + "'"));
|
||||
System.out.println("CONCURRENCY PASS clients=10 messages=100 unique=100");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void duplicateUsernameRace() throws Exception {
|
||||
String username = "race_" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String body = userBody(username, "Гонка");
|
||||
int threads = 16;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
CyclicBarrier barrier = new CyclicBarrier(threads);
|
||||
List<Future<Integer>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < threads; i++) {
|
||||
futures.add(pool.submit(() -> {
|
||||
barrier.await();
|
||||
return call("POST", "/api/v1/users", null, body).status;
|
||||
}));
|
||||
}
|
||||
int created = 0;
|
||||
int conflict = 0;
|
||||
for (Future<Integer> future : futures) {
|
||||
int status = future.get();
|
||||
if (status == 201) {
|
||||
created++;
|
||||
} else if (status == 409) {
|
||||
conflict++;
|
||||
} else {
|
||||
throw new AssertionError("unexpected status " + status);
|
||||
}
|
||||
}
|
||||
pool.shutdown();
|
||||
assertEquals(1, created);
|
||||
assertEquals(threads - 1, conflict);
|
||||
assertEquals(1, queryInt("SELECT count(*) FROM users WHERE username = '" + username + "'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void chatCreateRollsBack() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
JsonNode alice = register("rb_a_" + suffix, "Алиса");
|
||||
JsonNode bob = register("rb_b_" + suffix, "Боб");
|
||||
String token = login("rb_a_" + suffix);
|
||||
int before = queryInt("SELECT count(*) FROM chats");
|
||||
try (Connection conn = open(); Statement statement = conn.createStatement()) {
|
||||
statement.execute("""
|
||||
CREATE OR REPLACE FUNCTION lab_fail_second_member() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.position > 0 THEN
|
||||
RAISE EXCEPTION 'forced rollback';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$
|
||||
""");
|
||||
statement.execute("""
|
||||
CREATE TRIGGER lab_fail_second_member
|
||||
BEFORE INSERT ON chat_members
|
||||
FOR EACH ROW EXECUTE FUNCTION lab_fail_second_member()
|
||||
""");
|
||||
}
|
||||
try {
|
||||
Resp chat = call("POST", "/api/v1/chats", token, "{\"title\":\"Сломанный\",\"member_ids\":[\""
|
||||
+ alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}");
|
||||
assertEquals(500, chat.status);
|
||||
assertEquals(before, queryInt("SELECT count(*) FROM chats"));
|
||||
assertEquals(before, queryInt("SELECT count(DISTINCT chat_id) FROM chat_members"));
|
||||
} finally {
|
||||
try (Connection conn = open(); Statement statement = conn.createStatement()) {
|
||||
statement.execute("DROP TRIGGER IF EXISTS lab_fail_second_member ON chat_members");
|
||||
statement.execute("DROP FUNCTION IF EXISTS lab_fail_second_member()");
|
||||
}
|
||||
}
|
||||
Resp recovered = call("POST", "/api/v1/chats", token, "{\"title\":\"После отката\",\"member_ids\":[\""
|
||||
+ alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}");
|
||||
assertEquals(201, recovered.status);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void expiryLogoutAndWrongPassword() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
register("ttl_" + suffix, "Короткий");
|
||||
String redisUrl = "redis://127.0.0.1:" + redisPort + "/0";
|
||||
List<String> localLogs = new CopyOnWriteArrayList<>();
|
||||
MessengerServer shortServer = MessengerServer.start(new Config(
|
||||
"127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 2, 4),
|
||||
localLogs::add, localLogs::add);
|
||||
try {
|
||||
String shortBase = "http://127.0.0.1:" + shortServer.port();
|
||||
Resp session = callAt(shortBase, "POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
||||
basic("ttl_" + suffix, "password-ok-12"));
|
||||
assertEquals(201, session.status);
|
||||
JsonNode body = JSON.readTree(session.body);
|
||||
assertTrue(Instant.parse(body.get("expires_at").asText()).isAfter(Instant.now()));
|
||||
String token = body.get("token").asText();
|
||||
Thread.sleep(3500);
|
||||
Resp expired = callAt(shortBase, "GET", "/api/v1/users/me", token, null, null, null);
|
||||
assertEquals(401, expired.status);
|
||||
} finally {
|
||||
shortServer.stop();
|
||||
}
|
||||
|
||||
register("out_" + suffix, "Выход");
|
||||
String token = login("out_" + suffix);
|
||||
Resp denied = call("POST", "/api/v1/auth/sessions", null, null, "Authorization",
|
||||
basic("out_" + suffix, "definitely-wrong"));
|
||||
assertEquals(401, denied.status);
|
||||
Resp logout = call("DELETE", "/api/v1/auth/sessions/current", token, null);
|
||||
assertEquals(204, logout.status);
|
||||
assertTrue(logout.body.isEmpty());
|
||||
Resp again = call("GET", "/api/v1/users/me", token, null);
|
||||
assertEquals(401, again.status);
|
||||
Resp secondLogout = call("DELETE", "/api/v1/auth/sessions/current", token, null);
|
||||
assertEquals(401, secondLogout.status);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void dependencyLossDoesNotTrustAnonymous() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
register("dep_" + suffix, "Зависимость");
|
||||
String token = login("dep_" + suffix);
|
||||
docker("pause", REDIS_NAME);
|
||||
try {
|
||||
Resp ready = call("GET", "/health/ready", null, null);
|
||||
assertEquals(503, ready.status);
|
||||
assertTrue(ready.body.contains("unavailable"));
|
||||
Resp me = call("GET", "/api/v1/users/me", token, null);
|
||||
assertEquals(503, me.status);
|
||||
Resp anon = call("GET", "/api/v1/users/me", null, null);
|
||||
assertEquals(401, anon.status);
|
||||
} finally {
|
||||
docker("unpause", REDIS_NAME);
|
||||
}
|
||||
waitReady();
|
||||
assertEquals(200, call("GET", "/api/v1/users/me", token, null).status);
|
||||
|
||||
docker("pause", POSTGRES_NAME);
|
||||
try {
|
||||
Resp ready = call("GET", "/health/ready", null, null);
|
||||
assertEquals(503, ready.status);
|
||||
Resp me = call("GET", "/api/v1/users/me", token, null);
|
||||
assertEquals(503, me.status);
|
||||
} finally {
|
||||
docker("unpause", POSTGRES_NAME);
|
||||
}
|
||||
waitReady();
|
||||
assertEquals(200, call("GET", "/api/v1/users/me", token, null).status);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void historyIndexServesThePage() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
JsonNode user = register("hist_" + suffix, "История");
|
||||
String token = login("hist_" + suffix);
|
||||
Resp chat = call("POST", "/api/v1/chats", token,
|
||||
"{\"title\":\"Индекс\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}");
|
||||
UUID chatId = UUID.fromString(JSON.readTree(chat.body).get("id").asText());
|
||||
UUID sender = UUID.fromString(user.get("id").asText());
|
||||
Instant start = Instant.now().minusSeconds(60);
|
||||
try (Connection conn = open();
|
||||
PreparedStatement insert = conn.prepareStatement("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""")) {
|
||||
for (int i = 0; i < 10_000; i++) {
|
||||
insert.setObject(1, UUID.randomUUID());
|
||||
insert.setObject(2, chatId);
|
||||
insert.setObject(3, sender);
|
||||
insert.setString(4, "row-" + i);
|
||||
insert.setObject(5, OffsetDateTime.ofInstant(start.plusMillis(i), ZoneOffset.UTC));
|
||||
insert.addBatch();
|
||||
if (i % 500 == 499) {
|
||||
insert.executeBatch();
|
||||
}
|
||||
}
|
||||
insert.executeBatch();
|
||||
}
|
||||
Instant cursorTime;
|
||||
UUID cursorId;
|
||||
try (Connection conn = open();
|
||||
PreparedStatement statement = conn.prepareStatement("""
|
||||
SELECT id, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = ?
|
||||
ORDER BY created_at, id
|
||||
OFFSET 9900 LIMIT 1
|
||||
""")) {
|
||||
statement.setObject(1, chatId);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
cursorId = rows.getObject("id", UUID.class);
|
||||
cursorTime = rows.getObject("created_at", OffsetDateTime.class).toInstant();
|
||||
}
|
||||
}
|
||||
String plan = server.store().explainHistory(chatId, cursorTime, cursorId);
|
||||
Path evidence = Path.of("evidence", "explain-plan.txt");
|
||||
Files.createDirectories(evidence.getParent());
|
||||
Files.writeString(evidence, "messages=10000\n\n" + plan);
|
||||
assertTrue(plan.contains("messages_history_idx"), plan);
|
||||
assertTrue(plan.contains("Buffers:"), plan);
|
||||
assertFalse(plan.contains("Seq Scan"), plan);
|
||||
Resp page = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=50", token, null);
|
||||
assertEquals(200, page.status);
|
||||
assertEquals(50, JSON.readTree(page.body).get("items").size());
|
||||
System.out.println("EXPLAIN index=messages_history_idx rows=10000");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void shutdownKeepsLiveness() throws Exception {
|
||||
server.refuseNewRequests();
|
||||
assertEquals(200, call("GET", "/health/live", null, null).status);
|
||||
assertEquals(503, call("GET", "/health/ready", null, null).status);
|
||||
Resp post = call("POST", "/api/v1/users", null, userBody("after_stop", "Стоп"));
|
||||
assertEquals(503, post.status);
|
||||
}
|
||||
|
||||
|
||||
private static void docker(String... args) throws Exception {
|
||||
java.util.ArrayList<String> command = new java.util.ArrayList<>();
|
||||
command.add("docker");
|
||||
command.addAll(java.util.List.of(args));
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
if (process.waitFor() != 0 && !java.util.List.of(args).contains("-f")) {
|
||||
throw new IllegalStateException(String.join(" ", command) + " -> " + output);
|
||||
}
|
||||
}
|
||||
|
||||
private static void waitUntil(String container, String... exec) throws Exception {
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(40).toNanos();
|
||||
while (System.nanoTime() < deadline) {
|
||||
java.util.ArrayList<String> command = new java.util.ArrayList<>();
|
||||
command.add("docker");
|
||||
command.add("exec");
|
||||
command.add(container);
|
||||
command.addAll(java.util.List.of(exec));
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
process.getInputStream().readAllBytes();
|
||||
if (process.waitFor() == 0) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new IllegalStateException("container not ready: " + container);
|
||||
}
|
||||
|
||||
private static int publishedPort(String container, int port) throws Exception {
|
||||
Process process = new ProcessBuilder("docker", "port", container, port + "/tcp")
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
if (process.waitFor() != 0 || output.isEmpty()) {
|
||||
throw new IllegalStateException("no published port for " + container);
|
||||
}
|
||||
String first = output.split("\n")[0];
|
||||
return Integer.parseInt(first.substring(first.lastIndexOf(':') + 1));
|
||||
}
|
||||
|
||||
private static JsonNode register(String username, String displayName) throws Exception {
|
||||
Resp response = call("POST", "/api/v1/users", null, userBody(username, displayName));
|
||||
assertEquals(201, response.status, response.body);
|
||||
return JSON.readTree(response.body);
|
||||
}
|
||||
|
||||
private static String login(String username) throws Exception {
|
||||
Resp response = call("POST", "/api/v1/auth/sessions", null, null, "Authorization", basic(username, "password-ok-12"));
|
||||
assertEquals(201, response.status, response.body);
|
||||
return JSON.readTree(response.body).get("token").asText();
|
||||
}
|
||||
|
||||
private static String userBody(String username, String displayName) {
|
||||
return "{\"username\":\"" + username + "\",\"display_name\":\"" + displayName + "\",\"password\":\"password-ok-12\"}";
|
||||
}
|
||||
|
||||
private static String basic(String username, String password) {
|
||||
String raw = username + ":" + password;
|
||||
return "Basic " + Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String encode(String value) {
|
||||
return java.net.URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static void waitReady() throws Exception {
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(20).toNanos();
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (call("GET", "/health/ready", null, null).status == 200) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(300);
|
||||
}
|
||||
throw new AssertionError("ready did not recover");
|
||||
}
|
||||
|
||||
private static int queryInt(String sql) throws Exception {
|
||||
try (Connection conn = open();
|
||||
Statement statement = conn.createStatement();
|
||||
ResultSet rows = statement.executeQuery(sql)) {
|
||||
rows.next();
|
||||
return rows.getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection open() throws Exception {
|
||||
String plain = jdbcUrl.replaceAll("[?].*", "");
|
||||
return DriverManager.getConnection(plain, DB_USER, DB_PASSWORD);
|
||||
}
|
||||
|
||||
private static Resp call(String method, String path, String token, String json) throws Exception {
|
||||
return call(method, path, token, json, null, null);
|
||||
}
|
||||
|
||||
private static Resp call(String method, String path, String token, String json, String header, String headerValue) throws Exception {
|
||||
return callAt(base, method, path, token, json, header, headerValue);
|
||||
}
|
||||
|
||||
private static Resp callAt(
|
||||
String root,
|
||||
String method,
|
||||
String path,
|
||||
String token,
|
||||
String json,
|
||||
String header,
|
||||
String headerValue) throws Exception {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(root + path))
|
||||
.timeout(Duration.ofSeconds(12));
|
||||
if (token != null) {
|
||||
builder.header("Authorization", "Bearer " + token);
|
||||
}
|
||||
if (header != null) {
|
||||
builder.header(header, headerValue);
|
||||
}
|
||||
if (json != null) {
|
||||
builder.header("Content-Type", "application/json");
|
||||
builder.method(method, HttpRequest.BodyPublishers.ofString(json));
|
||||
} else if ("POST".equals(method) || "DELETE".equals(method)) {
|
||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
} else {
|
||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
}
|
||||
HttpResponse<String> response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
||||
return new Resp(
|
||||
response.statusCode(),
|
||||
response.body(),
|
||||
response.headers().firstValue("WWW-Authenticate").orElse(""),
|
||||
response.headers().firstValue("X-Request-Id").orElse(""));
|
||||
}
|
||||
|
||||
private record Resp(int status, String body, String challenge, String requestId) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.mtusi.lab2;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PasswordTest {
|
||||
@Test
|
||||
void longPasswordsAreNotTruncated() {
|
||||
Passwords passwords = new Passwords(4);
|
||||
String first = "п".repeat(80);
|
||||
String second = "п".repeat(79) + "я";
|
||||
String hash = passwords.hash(first);
|
||||
assertTrue(passwords.verify(first, hash));
|
||||
assertFalse(passwords.verify(second, hash));
|
||||
assertFalse(passwords.verify("other-password-value", hash));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user