#!/usr/bin/env python3 """PostgreSQL-backed, horizontally scalable HTTP API for lab3.""" import base64 import binascii from datetime import datetime, timedelta, timezone import hashlib import json import logging import os import re import secrets import signal import socket import sys import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, urlsplit import uuid from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError from psycopg.conninfo import make_conninfo from psycopg.errors import UniqueViolation from psycopg.rows import dict_row from psycopg.types.json import Jsonb import psycopg from psycopg_pool import ConnectionPool, PoolTimeout LOG = logging.getLogger("messenger") USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") MAX_BODY_BYTES = 1024 * 1024 IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") IDEMPOTENCY_TTL = timedelta(hours=24) MIGRATIONS = Path(__file__).resolve().parent / "migrations" PASSWORD_HASHER = PasswordHasher() POOL = None SESSION_TTL_SECONDS = 3600 INSTANCE_ID = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() or str(uuid.uuid4()) class ApiError(Exception): def __init__(self, status, code, message, headers=None): super().__init__(message) self.status = status self.code = code self.message = message self.headers = headers or {} def invalid(message="Некорректный запрос"): return ApiError(400, "invalid_request", message) def unauthorized(scheme): challenge = ('Basic realm="messenger", charset="UTF-8"' if scheme == "Basic" else 'Bearer realm="messenger"') return ApiError(401, "unauthorized", "Требуется действительная аутентификация", {"WWW-Authenticate": challenge}) def utc_now(): return datetime.now(timezone.utc) def timestamp(value): return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def user_json(row): return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": timestamp(row["created_at"]), } def chat_json(conn, row): members = conn.execute( "SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY member_position", (row["id"],), ).fetchall() return { "id": str(row["id"]), "title": row["title"], "member_ids": [str(member["user_id"]) for member in members], "created_at": timestamp(row["created_at"]), } def message_json(row): return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": timestamp(row["created_at"]), } def encode_cursor(kind, scope, created_at, object_id): payload = json.dumps( {"kind": kind, "scope": str(scope), "created_at": timestamp(created_at), "id": str(object_id)}, separators=(",", ":"), ).encode("utf-8") return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") def decode_cursor(value, kind, scope): try: padded = value + "=" * (-len(value) % 4) raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True) data = json.loads(raw.decode("utf-8")) if (not isinstance(data, dict) or set(data) != {"kind", "scope", "created_at", "id"} or data["kind"] != kind or data["scope"] != str(scope) or not isinstance(data["created_at"], str)): raise ValueError("invalid cursor fields") created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00")) if created_at.tzinfo is None: raise ValueError("cursor timestamp has no timezone") return created_at.astimezone(timezone.utc), uuid.UUID(data["id"]) except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error): raise invalid("Некорректный cursor") def parse_uuid(value, label): if not isinstance(value, str): raise invalid("Некорректный " + label) try: return uuid.UUID(value) except (ValueError, AttributeError): raise invalid("Некорректный " + label) def parse_limit(query): values = query.get("limit") if values is None: return 50 if len(values) != 1 or not re.fullmatch(r"[0-9]+", values[0]): raise invalid("Некорректный limit") value = int(values[0]) if not 1 <= value <= 100: raise invalid("Некорректный limit") return value def database_conninfo(): return make_conninfo( host=os.environ.get("PGHOST", "localhost"), port=os.environ.get("PGPORT", "5432"), dbname=os.environ.get("PGDATABASE", "messenger"), user=os.environ.get("PGUSER", "messenger"), password=os.environ.get("PGPASSWORD", ""), connect_timeout=3, application_name="mtusi-messenger-lab3", ) def migrate(pool): with pool.connection() as conn: conn.execute("SELECT pg_advisory_xact_lock(24012026, 2)") conn.execute( """CREATE TABLE IF NOT EXISTS schema_migrations ( version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() )""" ) applied = {row["version"] for row in conn.execute( "SELECT version FROM schema_migrations" ).fetchall()} for path in sorted(MIGRATIONS.glob("[0-9]*.sql")): if path.name in applied: continue sql = path.read_text(encoding="utf-8").strip() if not sql: raise RuntimeError("empty database migration: " + path.name) conn.execute(sql, prepare=False) conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,)) LOG.info("database migration applied version=%s", path.name) def validate_runtime_config(): try: ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) if ttl < 1 or ttl > 31_536_000: raise ValueError() max_connections = int(os.environ.get("DB_POOL_MAX_SIZE", "10")) if max_connections < 1 or max_connections > 100: raise ValueError() port = int(os.environ.get("APP_PORT", "8080")) if not 1 <= port <= 65535: raise ValueError() except ValueError: raise SystemExit("Invalid APP_PORT, SESSION_TTL_SECONDS or DB_POOL_MAX_SIZE") return ttl, max_connections, port class MessengerHandler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def do_GET(self): self._dispatch() def do_POST(self): self._dispatch() def do_DELETE(self): self._dispatch() def do_PUT(self): self._dispatch() def do_PATCH(self): self._dispatch() def do_OPTIONS(self): self._dispatch() def _dispatch(self): self.request_id = str(uuid.uuid4()) self.response_status = 500 try: path = urlsplit(self.path).path if self.command == "GET" and path == "/health/live": status, payload = 200, {"status": "ok"} else: with POOL.connection() as conn: status, payload = self._route(conn) self._send_json(status, payload) except ApiError as error: self._send_error(error.status, error.code, error.message, error.headers) except (psycopg.Error, PoolTimeout): LOG.warning("database unavailable request_id=%s", self.request_id) self._send_error(503, "unavailable", "Хранилище временно недоступно") except Exception as error: LOG.error("unhandled request error request_id=%s error_type=%s", self.request_id, type(error).__name__) self._send_error(500, "internal_error", "Внутренняя ошибка сервера") finally: LOG.info("request method=%s path=%s status=%s request_id=%s", self.command, urlsplit(self.path).path, self.response_status, self.request_id) def _send_json(self, status, payload): data = b"" if status == 204 else json.dumps( payload, ensure_ascii=False, separators=(",", ":") ).encode("utf-8") self.response_status = status self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.send_header("X-Request-Id", self.request_id) self.send_header("X-Instance-Id", INSTANCE_ID) self.send_header("Connection", "close") self.end_headers() if data: self.wfile.write(data) self.close_connection = True def _send_error(self, status, code, message, headers=None): data = json.dumps( {"error": {"code": code, "message": message, "request_id": self.request_id}}, ensure_ascii=False, separators=(",", ":"), ).encode("utf-8") self.response_status = status self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.send_header("X-Request-Id", self.request_id) self.send_header("X-Instance-Id", INSTANCE_ID) self.send_header("Connection", "close") for name, value in (headers or {}).items(): self.send_header(name, value) self.end_headers() self.wfile.write(data) self.close_connection = True def _read_json(self): content_type = self.headers.get("Content-Type", "") media_type = content_type.split(";", 1)[0].strip().lower() if media_type != "application/json": raise ApiError(415, "unsupported_media_type", "Ожидается application/json") length = self.headers.get("Content-Length") if length is None or not re.fullmatch(r"[0-9]+", length): raise invalid("Некорректный Content-Length") size = int(length) if size > MAX_BODY_BYTES: raise ApiError(413, "payload_too_large", "Тело запроса слишком велико") try: raw = self.rfile.read(size) if len(raw) != size: raise ValueError("incomplete body") def object_without_duplicates(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate JSON key") result[key] = value return result value = json.loads( raw.decode("utf-8"), object_pairs_hook=object_without_duplicates, parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)), ) except (ValueError, UnicodeError): raise invalid("Некорректный JSON") if not isinstance(value, dict): raise invalid("JSON body должен быть объектом") return value def _require_fields(self, data, required): if set(data) != set(required): raise invalid("Неверный набор полей") def _query(self): try: return parse_qs(urlsplit(self.path).query, keep_blank_values=True, strict_parsing=True) except ValueError: raise invalid("Некорректная строка запроса") def _current_identity(self, conn): authorization = self.headers.get("Authorization", "") if not authorization.startswith("Bearer "): raise unauthorized("Bearer") token = authorization[len("Bearer "):] if not token or len(token) > 512: raise unauthorized("Bearer") digest = hashlib.sha256(token.encode("utf-8")).hexdigest() row = conn.execute( """SELECT u.id FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = %s AND s.expires_at > now()""", (digest,), ).fetchone() if row is None: raise unauthorized("Bearer") return row["id"], digest def _idempotency_key(self): values = self.headers.get_all("Idempotency-Key", []) if len(values) != 1 or not IDEMPOTENCY_KEY_RE.fullmatch(values[0]): raise invalid("Некорректный Idempotency-Key") return values[0] def _create_idempotent_message(self, conn, user_id, chat_id, request_path, body, key): canonical_body = json.dumps( body, ensure_ascii=False, sort_keys=True, separators=(",", ":") ).encode("utf-8") request_hash = hashlib.sha256(canonical_body).hexdigest() conn.execute("DELETE FROM idempotency_records WHERE expires_at <= now()") claimed = conn.execute( """INSERT INTO idempotency_records (user_id, http_method, request_path, idempotency_key, request_hash, expires_at) VALUES (%s, 'POST', %s, %s, %s, now() + %s) ON CONFLICT (user_id, http_method, request_path, idempotency_key) DO UPDATE SET request_hash = EXCLUDED.request_hash, response_status = NULL, response_body = NULL, created_at = now(), expires_at = EXCLUDED.expires_at WHERE idempotency_records.expires_at <= now() RETURNING idempotency_key""", (user_id, request_path, key, request_hash, IDEMPOTENCY_TTL), ).fetchone() if claimed is None: existing = conn.execute( """SELECT request_hash, response_status, response_body FROM idempotency_records WHERE user_id = %s AND http_method = 'POST' AND request_path = %s AND idempotency_key = %s""", (user_id, request_path, key), ).fetchone() if existing is None: raise ApiError(503, "unavailable", "Повтор запроса временно недоступен") if existing["request_hash"] != request_hash: raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим телом") if existing["response_status"] is None or existing["response_body"] is None: raise ApiError(503, "unavailable", "Результат запроса временно недоступен") return existing["response_status"], existing["response_body"] row = conn.execute( """INSERT INTO messages (chat_id, sender_id, text) VALUES (%s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at""", (chat_id, user_id, body["text"]), ).fetchone() payload = message_json(row) conn.execute( """UPDATE idempotency_records SET response_status = 201, response_body = %s WHERE user_id = %s AND http_method = 'POST' AND request_path = %s AND idempotency_key = %s""", (Jsonb(payload), user_id, request_path, key), ) return 201, payload def _create_session(self, conn): authorization = self.headers.get("Authorization", "") if not authorization.startswith("Basic "): raise unauthorized("Basic") length = self.headers.get("Content-Length", "0") if not re.fullmatch(r"[0-9]+", length) or int(length) != 0: raise invalid("Создание сессии не принимает тело запроса") try: encoded = authorization[len("Basic "):] decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8") username, password = decoded.split(":", 1) except (ValueError, UnicodeError, binascii.Error): raise unauthorized("Basic") if not USERNAME_RE.fullmatch(username): raise unauthorized("Basic") row = conn.execute( "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", (username,), ).fetchone() valid = False if row is not None: try: valid = PASSWORD_HASHER.verify(row["password_hash"], password) except (VerifyMismatchError, VerificationError, InvalidHashError): valid = False if not valid: raise unauthorized("Basic") token = secrets.token_urlsafe(32) expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS) conn.execute( "INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)", (hashlib.sha256(token.encode("utf-8")).hexdigest(), row["id"], expires_at), ) return 201, { "token": token, "token_type": "Bearer", "expires_at": timestamp(expires_at), "user": user_json(row), } def _route(self, conn): parsed = urlsplit(self.path) path = parsed.path if self.command == "GET" and path == "/health/ready": conn.execute("SELECT 1") return 200, {"status": "ok"} if self.command == "POST" and path == "/api/v1/users": body = self._read_json() self._require_fields(body, {"username", "display_name", "password"}) username, display_name, password = body["username"], body["display_name"], body["password"] if not isinstance(username, str) or not USERNAME_RE.fullmatch(username): raise invalid("Некорректный username") if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100: raise invalid("Некорректный display_name") if not isinstance(password, str) or not 12 <= len(password) <= 128: raise invalid("Некорректный password") password_hash = PASSWORD_HASHER.hash(password) try: row = conn.execute( """INSERT INTO users (username, display_name, password_hash) VALUES (%s, %s, %s) RETURNING id, username, display_name, created_at""", (username, display_name, password_hash), ).fetchone() except UniqueViolation: raise ApiError(409, "conflict", "Username уже занят") return 201, user_json(row) if self.command == "POST" and path == "/api/v1/auth/sessions": return self._create_session(conn) if self.command == "DELETE" and path == "/api/v1/auth/sessions/current": _, digest = self._current_identity(conn) conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) return 204, None user_id, _ = self._current_identity(conn) if self.command == "GET" and path == "/api/v1/users/me": row = conn.execute( "SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,), ).fetchone() return 200, user_json(row) if self.command == "POST" and path == "/api/v1/chats": body = self._read_json() self._require_fields(body, {"title", "member_ids"}) title, member_ids = body["title"], body["member_ids"] if not isinstance(title, str) or not title.strip() or len(title) > 100: raise invalid("Некорректный title") if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100: raise invalid("Некорректный member_ids") normalized = [parse_uuid(item, "member_id") for item in member_ids] if len(set(normalized)) != len(normalized): raise invalid("member_ids содержит дубликаты") if user_id not in normalized: raise invalid("Создатель должен входить в чат") found = conn.execute( "SELECT id FROM users WHERE id = ANY(%s::uuid[])", (normalized,), ).fetchall() if len(found) != len(normalized): raise invalid("Неизвестный участник чата") chat = conn.execute( "INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at", (title,), ).fetchone() for position, member_id in enumerate(normalized): conn.execute( "INSERT INTO chat_members (chat_id, user_id, member_position) VALUES (%s, %s, %s)", (chat["id"], member_id, position), ) return 201, chat_json(conn, chat) if self.command == "GET" and path == "/api/v1/chats": query = self._query() limit = parse_limit(query) cursors = query.get("cursor") if cursors is not None and (len(cursors) != 1 or not cursors[0]): raise invalid("Некорректный cursor") after = decode_cursor(cursors[0], "chats", user_id) if cursors else None sql = """SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s""" params = [user_id] if after is not None: sql += " AND (c.created_at, c.id) > (%s, %s)" params.extend(after) sql += " ORDER BY c.created_at, c.id LIMIT %s" params.append(limit + 1) rows = conn.execute(sql, params).fetchall() has_more = len(rows) > limit selected = rows[:limit] items = [chat_json(conn, row) for row in selected] next_cursor = None if has_more: last = selected[-1] next_cursor = encode_cursor("chats", user_id, last["created_at"], last["id"]) return 200, {"items": items, "next_cursor": next_cursor} chat_match = re.fullmatch(r"/api/v1/chats/([^/]+)(?:/messages)?", path) if chat_match: chat_id = parse_uuid(chat_match.group(1), "chat_id") chat = conn.execute( """SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s AND m.user_id = %s""", (chat_id, user_id), ).fetchone() if chat is None: raise ApiError(404, "not_found", "Объект не найден") is_messages_path = path.endswith("/messages") if not is_messages_path and self.command == "GET": return 200, chat_json(conn, chat) if is_messages_path and self.command == "POST": key = self._idempotency_key() body = self._read_json() self._require_fields(body, {"text"}) text = body["text"] if not isinstance(text, str) or not text.strip() or len(text) > 4000: raise invalid("Некорректный text") return self._create_idempotent_message( conn, user_id, chat_id, path, body, key ) if is_messages_path and self.command == "GET": query = self._query() limit = parse_limit(query) cursors = query.get("cursor") if cursors is not None and (len(cursors) != 1 or not cursors[0]): raise invalid("Некорректный cursor") after = decode_cursor(cursors[0], "messages", chat_id) if cursors else None sql = """SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s""" params = [chat_id] if after is not None: sql += " AND (created_at, id) > (%s, %s)" params.extend(after) sql += " ORDER BY created_at, id LIMIT %s" params.append(limit + 1) rows = conn.execute(sql, params).fetchall() has_more = len(rows) > limit selected = rows[:limit] items = [message_json(row) for row in selected] next_cursor = None if has_more: last = selected[-1] next_cursor = encode_cursor("messages", chat_id, last["created_at"], last["id"]) return 200, {"items": items, "next_cursor": next_cursor} raise ApiError(404, "not_found", "Объект не найден") def log_message(self, format_string, *args): return class MessengerServer(ThreadingHTTPServer): daemon_threads = False allow_reuse_address = True def main(): global POOL, SESSION_TTL_SECONDS logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") SESSION_TTL_SECONDS, max_connections, port = validate_runtime_config() mode = sys.argv[1] if len(sys.argv) > 1 else "serve" if mode not in ("serve", "migrate") or len(sys.argv) > 2: raise SystemExit("Usage: app.py [serve|migrate]") host = os.environ.get("APP_HOST", "0.0.0.0") POOL = ConnectionPool( conninfo=database_conninfo(), min_size=1, max_size=max_connections, timeout=5, kwargs={"row_factory": dict_row}, open=False, ) try: POOL.open(wait=True, timeout=15) if mode == "migrate": migrate(POOL) POOL.close() LOG.info("database migrations complete") return with POOL.connection() as conn: conn.execute("SELECT 1") except Exception as error: POOL.close() LOG.error("database initialization failed error_type=%s", type(error).__name__) raise SystemExit("Database unavailable or migrations failed") server = MessengerServer((host, port), MessengerHandler) LOG.info( "messenger starting host=%s port=%s storage=postgresql instance_id=%s", host, port, INSTANCE_ID, ) def request_shutdown(signum, frame): threading.Thread(target=server.shutdown, daemon=True).start() signal.signal(signal.SIGTERM, request_shutdown) signal.signal(signal.SIGINT, request_shutdown) try: server.serve_forever() finally: server.server_close() POOL.close() LOG.info("messenger stopped") if __name__ == "__main__": main()