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 info; private final Consumer error; private final int port; private MessengerServer(Config config, Consumer info, Consumer 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 info, Consumer 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 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 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 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 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 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 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 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> 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 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 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 int writeSlice( HttpExchange exchange, String requestId, List loaded, int limit, String kind, UUID scope, java.util.function.Function createdAt, java.util.function.Function id, java.util.function.Function 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) { } }