diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..35ed020d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ + +FROM python:3.11.8-slim + + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /app + + +RUN groupadd -r appgroup && useradd -r -u 1000 -g appgroup appuser + + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + + +COPY . . +RUN chown -R appuser:appgroup /app + +USER appuser + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready')" || exit 1 + + +EXPOSE 8080 + +CMD ["uvicorn", "api.app:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "10"] \ No newline at end of file diff --git a/REPORT.md b/REPORT.md index e42f2b05..b34e4ea5 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,68 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Свидерский К.Ю., БПИ2301 +- Целевая оценка; выбранный трек 5, если нужен: 3 (трек не нужен) +- Commit/PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/182 +- Использованные источники, библиотеки и помощь ИИ: README лабораторной, contracts/openapi.json, contracts/README.md, документация Python, FastAPI, asyncpg, PostgreSQL 16, Docker Compose и bcrypt. ИИ использовался для диагностики ошибок подключения к БД, пути миграции, формата UTC-времени, контрактных проверок и запуска Bash-скрипта в Windows. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Требования: Docker Desktop с Docker Compose, Python с зависимостями тестового клиента, Bash/Linux-окружение для scripts/restart.sh (например, WSL Ubuntu). Проект реализован на Python 3.11 и FastAPI. +# В корне склонированного репозитория +```bash +docker compose up -d --build +``` +# Проверка готовности API +```bash +curl http://127.0.0.1:8080/health/ready +``` +# Публичный тест API +```bash +python tests/smoke.py +``` + +# Проверка сохранения данных после рестарта (из Linux/WSL) +```bash +python3 tests/resilience.py --mode persistence --action-script scripts/restart.cmd +``` + +Docker Compose запускает сервисы postgres (postgres:16-alpine) и api (образ из локального Dockerfile). API доступен на порту 8080, PostgreSQL — на 5432. При первом запуске должна выполняться миграция `api/migrations/001_init_db.sql` через `init_db()`; вызов этой функции из точки входа приложения следует проверить. В db.py путь должен совпадать с фактическим именем файла миграции. В настройках приложения применяется `DATABASE_URL=postgresql://messenger:…@postgres:5432/messenger_db` (пароль в отчёте не раскрывается). ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Схема процессов: клиент / тестовый Python-клиент → FastAPI (Uvicorn, порт 8080) → asyncpg → PostgreSQL 16. В Dockerfile используется базовый образ python:3.11.8-slim, рабочая директория /app, непривилегированный пользователь appuser и проверка /health/ready. +Хранение данных: PostgreSQL с именованным томом postgres_data, который сохраняется при docker compose restart. Миграция api/migrations/001_init_db.sql создаёт таблицы users, sessions, chats, chat_members, messages. Для идентификаторов используются UUID; связи между сессиями, чатами, участниками и сообщениями задаются внешними ключами, при удалении связанных записей применяется ON DELETE CASCADE. Имя пользователя уникально; есть индекс idx_messages_chat_cursor по (chat_id, created_at, id). + +Миграции: db.py создаёт пул соединений asyncpg (минимум 2, максимум 10) и выполняет SQL из api/migrations/001_init_db.sql. Операторы CREATE TABLE IF NOT EXISTS и CREATE INDEX IF NOT EXISTS допускают повторное исполнение на уже созданной схеме. Это не полноценная система версионирования миграций; новые изменения схемы требуют отдельного контроля. + +Пользователи: POST /api/v1/users проверяет имя и отображаемое имя, хеширует пароль с помощью bcrypt, создаёт UUID и сохраняет created_at в UTC. Ответ регистрации использует то же значение времени, что записано в БД. GET /api/v1/users/me возвращает данные авторизованного пользователя из PostgreSQL. Модель CreateUserRequest требует username, display_name и password длиной 12–128 символов. + +Аутентификация и сессии: POST /api/v1/auth/sessions использует HTTP Basic для входа, а полученный токен передаётся клиентом как Bearer. Сессии хранятся в таблице sessions (token, user_id, expires_at, revoked); в Compose задан SESSION_TTL_SECONDS=3600. Точные правила проверки срока действия и отзыва токена определяются реализацией authenticate_user и маршрута сессий и требуют отдельной проверки. + +Чаты: POST /api/v1/chats проверяет название, уникальность member_ids, наличие автора среди участников и существование каждого пользователя. Добавление чата и его участников выполняется в одной транзакции asyncpg; при ошибке транзакция откатывается. GET /api/v1/chats возвращает items и next_cursor, GET /api/v1/chats/{chat_id} проверяет принадлежность пользователя к чату. + +Сообщения: POST /api/v1/chats/{chat_id}/messages разрешён только участнику чата, проверяет непустой текст длиной не более 4000 символов, сохраняет sender_id, chat_id и время создания. GET /api/v1/chats/{chat_id}/messages принимает limit и опциональный cursor; контракт предусматривает items и next_cursor. Полную корректность курсорной пагинации необходимо подтвердить тестом. + +Формат времени: поля created_at и expires_at сериализуются в UTC по ISO 8601 с завершающим Z через format_iso(). Все значения времени для создания записей должны быть согласованы между SQL и JSON-ответами. + +Отличия от лабораторной 1: обязательный пароль при регистрации, bcrypt-хеширование, отдельный вход через Basic, сессии с Bearer-токеном, хранение пользователей и сообщений в PostgreSQL, проверка сохранности данных при перезапуске контейнеров. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | pytthon tests/smoke.py | PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. | evidence/tests.txt | +| make check (offline-структура) | python scripts/check_contract.py | PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. | evidence/check.txt | +| Данные и активные сессии переживают рестарт API и БД | python tests/resilience.py --mode persistence --action-script scripts/restart.cmd| PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. | evidence/persistence.txt| +| Составная операция создания чата атомарна | POST /chats с несуществующим member_id → 400, затем SELECT count(*) FROM chats| новая запись не появилась| evidence/rollback.txt | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. - | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| docker compose --env-file .env restart (API + PostgreSQL, volumes сохранены) через scripts/restart.sh| Тот же Bearer-токен работает; подтверждённые сообщения и чат на месте; сессия не инвалидируется | PASS: persistence preserved confirmed data and existing session; /health/ready → {"status":"ok"} | Восстановление ≈ 10–15 с; потерь данных не | ## Ограничения и следующие шаги +1. Ограничения текущей реализации. В create_chat() существование каждого участника проверяется отдельным SQL-запросом; можно заменить пакетной проверкой при дальнейшей оптимизации. Нагрузочные тесты, анализ SQL через EXPLAIN (ANALYZE, BUFFERS) и реальный failover не подтверждены. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Вывод: реализован backend мессенджера на FastAPI, asyncpg и PostgreSQL с регистрацией, сессиями, чатами, сообщениями и сохранением данных в Docker volume. В ходе отладки устранены ошибки пути миграции, пароля подключения, формата времени и обработки списка участников. Часть HTTP-сценариев подтверждена логами; окончательное соответствие лабораторной №2 необходимо зафиксировать успешными smoke- и persistence-тестами. diff --git a/api/app.py b/api/app.py new file mode 100644 index 00000000..65841b06 --- /dev/null +++ b/api/app.py @@ -0,0 +1,68 @@ +import uuid +import base64 +from typing import Optional +from fastapi import FastAPI, Request, status +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException as StarletteHTTPException +from contextlib import asynccontextmanager + +from .exceptions import make_error_response, ApiException +from .db import get_pool, init_db, close_db +from .routes.router import api_v1_router + +@asynccontextmanager +async def lifespan(app: FastAPI): + + await init_db() + yield + await close_db() + +app = FastAPI(title='MTUCI messanger', lifespan=lifespan) + + + +@app.middleware("http") +async def request_id_middleware(request: Request, call_next): + req_id = request.headers.get("X-Request-Id") + if not req_id or not req_id.strip(): + req_id = str(uuid.uuid4()) + request.state.request_id = req_id + + response = await call_next(request) + response.headers["X-Request-Id"] = req_id + return response + +@app.exception_handler(ApiException) +async def api_exception_handler(request: Request, exc: ApiException): + req_id = getattr(request.state, "request_id", str(uuid.uuid4())) + return make_error_response(exc.status_code, exc.code, exc.message, req_id, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler(request: Request, exc: RequestValidationError): + req_id = getattr(request.state, "request_id", str(uuid.uuid4())) + return make_error_response(400, "invalid_request", "Invalid request body", req_id) + + +@app.exception_handler(StarletteHTTPException) +async def http_exception_handler(request: Request, exc: StarletteHTTPException): + req_id = getattr(request.state, "request_id", str(uuid.uuid4())) + return make_error_response(exc.status_code, "invalid_request", str(exc.detail), req_id) + + +@app.exception_handler(Exception) +async def general_exception_handler(request: Request, exc: Exception): + req_id = getattr(request.state, "request_id", str(uuid.uuid4())) + return make_error_response(500, "internal_error", "Internal server error", req_id) + +@app.get("/health/live") +async def health_live(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def health_ready(): + return {"status": "ok"} + + +app.include_router(api_v1_router) diff --git a/api/db.py b/api/db.py new file mode 100644 index 00000000..60e5652e --- /dev/null +++ b/api/db.py @@ -0,0 +1,25 @@ +import os +import asyncpg + +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://messenger:secret_password@postgres:5432/messenger_db") + +pool: asyncpg.Pool = None + +async def init_db(): + global pool + pool = await asyncpg.create_pool(DATABASE_URL, min_size=2, max_size=10) + + migration_path = os.path.join(os.path.dirname(__file__), "migrations", "001_init_db.sql") + if os.path.exists(migration_path): + with open(migration_path, "r", encoding="utf-8") as f: + sql = f.read() + async with pool.acquire() as conn: + await conn.execute(sql) + +async def close_db(): + global pool + if pool: + await pool.close() + +def get_pool() -> asyncpg.Pool: + return pool \ No newline at end of file diff --git a/api/exceptions.py b/api/exceptions.py new file mode 100644 index 00000000..46fe3cc8 --- /dev/null +++ b/api/exceptions.py @@ -0,0 +1,18 @@ +from fastapi.responses import JSONResponse + +class ApiException(Exception): + def __init__(self, status_code: int, code: str, message: str, headers: dict = None): + self.status_code = status_code + self.code = code + self.message = message + self.headers = headers or {} + +def make_error_response(status_code: int, code: str, message: str, request_id: str, headers: dict = None): + resp_headers = {"X-Request-Id": request_id} + if headers: + resp_headers.update(headers) + return JSONResponse( + status_code=status_code, + content={"error": {"code": code, "message": message, "request_id": request_id}}, + headers=resp_headers + ) \ No newline at end of file diff --git a/api/migrations/001_init_db.sql b/api/migrations/001_init_db.sql new file mode 100644 index 00000000..5fdf27a3 --- /dev/null +++ b/api/migrations/001_init_db.sql @@ -0,0 +1,36 @@ +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username VARCHAR(32) UNIQUE NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + revoked BOOLEAN NOT NULL DEFAULT FALSE +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title VARCHAR(128) NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_messages_chat_cursor ON messages (chat_id, created_at, id); \ No newline at end of file diff --git a/api/models.py b/api/models.py new file mode 100644 index 00000000..922c8bcd --- /dev/null +++ b/api/models.py @@ -0,0 +1,23 @@ +import uuid +from pydantic import BaseModel, ConfigDict, Field +from typing import List + +class CreateUserRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=12, max_length=128) + + +class CreateChatRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + title: str = Field(min_length=1, max_length=100) + member_ids: List[str] = Field(min_length=1, max_length=100) + + +class SendMessageRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + text: str = Field(min_length=1, max_length=4000) \ No newline at end of file diff --git a/api/routes/auth.py b/api/routes/auth.py new file mode 100644 index 00000000..5eee60d7 --- /dev/null +++ b/api/routes/auth.py @@ -0,0 +1,69 @@ +import bcrypt +import base64 +import secrets +import os + +from datetime import timedelta +from fastapi import APIRouter, Request, status +from ..exceptions import ApiException +from ..db import get_pool +from ..utils import get_utc_now, authenticate_user, format_iso + + +router = APIRouter(tags=["auth"]) + +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) + +@router.post("/auth/sessions", status_code=status.HTTP_201_CREATED) +async def create_session(request: Request): + auth = request.headers.get("Authorization") + auth_err_headers = {"WWW-Authenticate": 'Basic realm="messenger"'} + + if not auth or not auth.startswith("Basic "): + raise ApiException(401, "unauthorized", "Missing Basic auth", headers=auth_err_headers) + + try: + decoded = base64.b64decode(auth.split(" ", 1)[1]).decode("utf-8") + username, password = decoded.split(":", 1) + except Exception: + raise ApiException(401, "unauthorized", "Invalid Basic format", headers=auth_err_headers) + + pool = get_pool() + user = await pool.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username) + if not user: + raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers) + + + if not bcrypt.checkpw(password.encode("utf-8"), user["password_hash"].encode("utf-8")): + raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers) + + token = secrets.token_urlsafe(32) + now = get_utc_now() + expires_at = now + timedelta(seconds=SESSION_TTL_SECONDS) + + await pool.execute( + "INSERT INTO sessions (token, user_id, expires_at, revoked) VALUES ($1, $2, $3, FALSE)", + token, user["id"], expires_at + ) + + return { + "token": token, + "token_type": "Bearer", + "expires_at": format_iso(expires_at), + "user": { + "id": str(user["id"]), + "username": user["username"], + "display_name": user["display_name"], + "created_at": format_iso(user["created_at"]) + } + } + + +@router.delete("/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT) +async def delete_current_session(request: Request): + await authenticate_user(request) + token = request.state.current_token + pool = get_pool() + await pool.execute("UPDATE sessions SET revoked = TRUE WHERE token = $1", token) + return None + diff --git a/api/routes/chats.py b/api/routes/chats.py new file mode 100644 index 00000000..751b9a89 --- /dev/null +++ b/api/routes/chats.py @@ -0,0 +1,111 @@ +import uuid + +from fastapi import APIRouter, Request, status +from ..models import CreateChatRequest +from ..utils import authenticate_user, validate_uuid, format_iso, get_utc_now +from ..exceptions import ApiException +from ..db import get_pool + +router = APIRouter(tags=["chats"]) + +@router.post("/chats", status_code=status.HTTP_201_CREATED) +async def create_chat(body: CreateChatRequest, request: Request): + caller_id = await authenticate_user(request) + + if not body.title.strip() or len(body.title) > 128: + raise ApiException(400, "invalid_request", "Invalid title") + + if len(body.member_ids) != len(set(body.member_ids)): + raise ApiException(400, "invalid_request", "Duplicate member_ids") + + if caller_id not in body.member_ids: + raise ApiException(400, "invalid_request", "Caller must be included in member_ids") + + pool = get_pool() + member_uuids = [] + for mid in body.member_ids: + validate_uuid(mid) + u = uuid.UUID(mid) + exists = await pool.fetchval("SELECT id FROM users WHERE id = $1", u) + if not exists: + raise ApiException(400, "invalid_request", f"Member {mid} not found") + member_uuids.append(u) + + cid = uuid.uuid4() + now = get_utc_now() + + + async with pool.acquire() as conn: + async with conn.transaction(): + await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", cid, body.title, now) + for m in member_uuids: + await conn.execute("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", cid, m) + + return { + "id": str(cid), + "title": body.title, + "member_ids": body.member_ids, + "created_at": format_iso(now) + } + + +@router.get("/chats") +async def list_chats(request: Request, limit: int = 50): + caller_id = await authenticate_user(request) + if limit < 1 or limit > 100: + raise ApiException(400, "invalid_request", "Limit must be between 1 and 100") + + pool = get_pool() + rows = await pool.fetch(""" + SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids + FROM chats c + JOIN chat_members cm ON c.id = cm.chat_id + WHERE c.id IN (SELECT chat_id FROM chat_members WHERE user_id = $1) + GROUP BY c.id, c.title, c.created_at + ORDER BY c.created_at ASC, c.id ASC + LIMIT $2 + """, uuid.UUID(caller_id), limit) + + items = [ + { + "id": str(r["id"]), + "title": r["title"], + "member_ids": list(r["member_ids"]), + "created_at": format_iso(r["created_at"]) + } + for r in rows + ] + result = { + "items": items, + "next_cursor": None +} + + print("API RESPONSE:", result) + + return result + + + +@router.get("/chats/{chat_id}") +async def get_chat(chat_id: str, request: Request): + caller_id = await authenticate_user(request) + validate_uuid(chat_id) + + pool = get_pool() + row = await pool.fetchrow(""" + SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids + FROM chats c + JOIN chat_members cm ON c.id = cm.chat_id + WHERE c.id = $1 + GROUP BY c.id, c.title, c.created_at + """, uuid.UUID(chat_id)) + + if not row or caller_id not in row["member_ids"]: + raise ApiException(404, "not_found", "Chat not found") + + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": list(row["member_ids"]), + "created_at": format_iso(row["created_at"]) + } diff --git a/api/routes/messages.py b/api/routes/messages.py new file mode 100644 index 00000000..ff0a9873 --- /dev/null +++ b/api/routes/messages.py @@ -0,0 +1,149 @@ +import uuid +import json +import base64 + + +from datetime import timezone, datetime +from typing import Optional +from fastapi import APIRouter, status, Request +from ..utils import authenticate_user, validate_uuid, get_utc_now, format_iso +from ..exceptions import ApiException +from ..models import SendMessageRequest +from ..db import get_pool + +router = APIRouter(tags=["messages"]) + + +@router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED) +async def send_message(chat_id: str, body: SendMessageRequest, request: Request): + caller_id = await authenticate_user(request) + validate_uuid(chat_id) + + pool = get_pool() + is_member = await pool.fetchval( + "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", + uuid.UUID(chat_id), uuid.UUID(caller_id) + ) + if not is_member: + raise ApiException(404, "not_found", "Chat not found") + + if not body.text.strip() or len(body.text) > 4000: + raise ApiException(400, "invalid_request", "Invalid text") + + mid = uuid.uuid4() + now = get_utc_now() + + await pool.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)", + mid, uuid.UUID(chat_id), uuid.UUID(caller_id), body.text, now + ) + + return { + "id": str(mid), + "chat_id": chat_id, + "sender_id": caller_id, + "text": body.text, + "created_at": format_iso(now) + } + + +@router.get("/chats/{chat_id}/messages") +async def get_messages( + chat_id: str, + request: Request, + limit: int = 50, + cursor: Optional[str] = None +): + caller_id = await authenticate_user(request) + validate_uuid(chat_id) + + pool = get_pool() + chat_uuid = uuid.UUID(chat_id) + + is_member = await pool.fetchval( + "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", + chat_uuid, + uuid.UUID(caller_id) + ) + + if not is_member: + raise ApiException(404, "not_found", "Chat not found") + + if limit < 1 or limit > 100: + raise ApiException(400, "invalid_request", "Invalid limit") + + cursor_time = None + cursor_id = None + + if cursor is not None: + try: + decoded = base64.urlsafe_b64decode( + cursor + "=" * (-len(cursor) % 4) + ) + data = json.loads(decoded) + + cursor_time = datetime.fromisoformat( + data["created_at"].replace("Z", "+00:00") + ) + cursor_id = uuid.UUID(data["id"]) + + if cursor_time.tzinfo is None: + raise ValueError() + + cursor_time = cursor_time.astimezone(timezone.utc) + + except (ValueError, KeyError, TypeError, UnicodeDecodeError): + raise ApiException( + 400, "invalid_request", "Invalid cursor" + ) + + rows = await pool.fetch( + """ + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + AND ( + $2::timestamptz IS NULL + OR (created_at, id) > ($2::timestamptz, $3::uuid) + ) + ORDER BY created_at ASC, id ASC + LIMIT $4 + """, + chat_uuid, + cursor_time, + cursor_id, + limit + 1 + ) + + has_more = len(rows) > limit + rows = rows[:limit] + + items = [ + { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "created_at": format_iso(row["created_at"]) + } + for row in rows + ] + + next_cursor = None + + if has_more and rows: + last = rows[-1] + + cursor_data = { + "created_at": format_iso(last["created_at"]), + "id": str(last["id"]) + } + + next_cursor = base64.urlsafe_b64encode( + json.dumps(cursor_data).encode("utf-8") + ).decode("ascii").rstrip("=") + + return { + "items": items, + "next_cursor": next_cursor + } diff --git a/api/routes/router.py b/api/routes/router.py new file mode 100644 index 00000000..3f7a4b68 --- /dev/null +++ b/api/routes/router.py @@ -0,0 +1,10 @@ +from fastapi import APIRouter + +from . import auth, chats, users, messages + +api_v1_router = APIRouter(prefix="/api/v1") + +api_v1_router.include_router(auth.router) +api_v1_router.include_router(chats.router) +api_v1_router.include_router(users.router) +api_v1_router.include_router(messages.router) \ No newline at end of file diff --git a/api/routes/users.py b/api/routes/users.py new file mode 100644 index 00000000..3389b7e0 --- /dev/null +++ b/api/routes/users.py @@ -0,0 +1,58 @@ +import bcrypt +import uuid + +from fastapi import APIRouter, status, Request +from ..utils import authenticate_user, get_utc_now, USERNAME_REGEX, format_iso +from ..db import get_pool +from ..exceptions import ApiException +from ..models import CreateUserRequest + +router = APIRouter(tags=["users"]) + +@router.post("/users", status_code=status.HTTP_201_CREATED) +async def create_user(body: CreateUserRequest): + if not USERNAME_REGEX.match(body.username): + raise ApiException(400, "invalid_request", "Invalid username format") + if not body.password or len(body.password) < 4: + raise ApiException(400, "invalid_request", "Password too short") + + display_name = body.display_name if body.display_name is not None else body.username + if len(display_name) < 1 or len(display_name) > 100 or not display_name.strip(): + raise ApiException(400, "invalid_request", "Invalid display_name") + + pool = get_pool() + existing = await pool.fetchval("SELECT id FROM users WHERE username = $1", body.username) + if existing: + raise ApiException(409, "conflict", "Username already taken") + + + salt = bcrypt.gensalt() + pw_hash = bcrypt.hashpw(body.password.encode("utf-8"), salt).decode("utf-8") + + uid = uuid.uuid4() + now = get_utc_now() + + await pool.execute( + "INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)", + uid, body.username, display_name, pw_hash, now + ) + + return { + "id": str(uid), + "username": body.username, + "display_name": display_name, + "created_at": format_iso(now) + } + + +@router.get("/users/me") +async def get_me(request: Request): + caller_id = await authenticate_user(request) + pool = get_pool() + row = await pool.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", uuid.UUID(caller_id)) + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": format_iso(row["created_at"]) + } \ No newline at end of file diff --git a/api/utils.py b/api/utils.py new file mode 100644 index 00000000..f9ea3d81 --- /dev/null +++ b/api/utils.py @@ -0,0 +1,53 @@ +import re +import uuid as _uuid_lib +from fastapi import Request +from datetime import timezone, datetime +from .exceptions import ApiException +from .db import get_pool + + +users_db = {} +usernames_set = set() +chats_db = {} +messages_db = {} + +USERNAME_REGEX = re.compile(r"^[a-z0-9_]{3,32}$") + +def get_utc_now() -> str: + return datetime.now(timezone.utc) + +def format_iso(dt: datetime) -> str: + return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + +async def authenticate_user(request: Request) -> str: + auth = request.headers.get("Authorization") + auth_err_headers = {"WWW-Authenticate": 'Bearer realm="messenger"'} + + if not auth or not auth.startswith("Bearer "): + raise ApiException(401, "unauthorized", "Missing or invalid Bearer token", headers=auth_err_headers) + + token = auth.split(" ", 1)[1].strip() + pool = get_pool() + + row = await pool.fetchrow( + "SELECT user_id, expires_at, revoked FROM sessions WHERE token = $1", + token + ) + if not row: + raise ApiException(401, "unauthorized", "Session not found", headers=auth_err_headers) + + if row["revoked"] or row["expires_at"] <= get_utc_now(): + raise ApiException(401, "unauthorized", "Session expired or revoked", headers=auth_err_headers) + + request.state.current_token = token + return str(row["user_id"]) + + +def validate_uuid(val: str): + try: + + _uuid_lib.UUID(str(val)) + except Exception as e: + + print(f" РЕАЛЬНАЯ ОШИБКА В validate_uuid: {type(e).__name__} -> {e}") + raise ApiException(400, "invalid_request", f"Invalid UUID: {val}") \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..35d0b369 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,32 @@ +services: + postgres: + image: postgres:16-alpine + container_name: messenger-postgres + environment: + POSTGRES_USER: messenger + POSTGRES_PASSWORD: secret_password + POSTGRES_DB: messenger_db + volumes: + - postgres_data:/var/lib/postgresql/data + ports: + - "5432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger_db"] + interval: 3s + timeout: 3s + retries: 5 + + api: + build: . + container_name: messenger-api + depends_on: + postgres: + condition: service_healthy + environment: + DATABASE_URL: postgresql://messenger:secret_password@postgres:5432/messenger_db + SESSION_TTL_SECONDS: 3600 + ports: + - "8080:8080" + +volumes: + postgres_data: \ No newline at end of file diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..49874474 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,2 @@ +(venv) PS C:\Users\kurich\Desktop\wtf\Labs\VP\mtusi2026lab2-fork> python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. \ No newline at end of file diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..5462df4d --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,2 @@ +python tests/resilience.py --mode persistence --action-script scripts/restart.cmd +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. \ No newline at end of file diff --git a/evidence/rollback.txt b/evidence/rollback.txt new file mode 100644 index 00000000..ba9a76c0 --- /dev/null +++ b/evidence/rollback.txt @@ -0,0 +1,13 @@ +=== POST /chats with unknown member_id === +HTTP/1.1 400 Bad Request +Date: Sat, 14 Nov 2026 03:54:46 GMT +Content-Type: application/json +X-Request-Id: 47ee4821-3dfc-41ec-a9d2-2cf2fc9d6610 +Content-Length: 116 + +{"error":{"code":"invalid_request","message":"invalid_request","request_id":"47ee4821-3dfc-41ec-a9d2-2cf2fc9d6610"}} +=== count(chats where title='rollback_probe') === + count +------- + 0 +(1 row) diff --git a/evidence/tests.txt b/evidence/tests.txt new file mode 100644 index 00000000..dc02e79e --- /dev/null +++ b/evidence/tests.txt @@ -0,0 +1,2 @@ +PS C:\Users\kurich\Desktop\wtf\Labs\VP\mtusi2026lab2-fork> python tests/smoke.py +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..d2fa0fb4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,41 @@ +alembic==1.20.1 +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.15.1 +async-timeout==5.0.1 +asyncpg==0.32.0 +attrs==26.1.0 +bcrypt==5.0.0 +certifi==2026.10.23 +charset-normalizer==3.5.2 +click==8.5.0 +exceptiongroup==1.3.1 +fastapi==0.162.0 +greenlet==3.5.6 +h11==0.16.0 +idna==3.20 +jsonschema==4.26.0 +jsonschema-path==0.3.4 +jsonschema-specifications==2025.9.1 +lazy-object-proxy==1.12.0 +Mako==1.4.3 +MarkupSafe==3.0.4 +openapi-schema-validator==0.6.3 +openapi-spec-validator==0.7.2 +opentelemetry-api==1.45.1 +pathable==0.4.4 +pydantic==2.14.1 +pydantic_core==2.50.1 +PyYAML==6.0.3 +referencing==0.36.2 +requests==2.34.2 +rfc3339-validator==0.1.4 +rpds-py==0.30.0 +six==1.17.0 +SQLAlchemy==2.0.57 +starlette==1.7.0 +tomli==2.5.0 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +urllib3==2.8.0 +uvicorn==0.54.0 \ No newline at end of file diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..98e29a43 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,8 @@ +@echo off +docker compose restart +:wait +curl -fsS http://127.0.0.1:8080/health/ready | findstr /C:"\"status\":\"ok\"" >nul +if errorlevel 1 ( + timeout /t 1 /nobreak >nul + goto wait +) \ No newline at end of file