diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..268c1733 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,30 @@ +# --- build stage --- +FROM python:3.12-slim AS builder + +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir --prefix=/install -r requirements.txt + +# --- runtime stage --- +FROM python:3.12-slim + +# Непривилегированный пользователь +RUN useradd --create-home --shell /bin/bash appuser + +WORKDIR /app +COPY --from=builder /install /usr/local +COPY src/ ./src/ +COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh + +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 + +USER appuser +EXPOSE 8080 + +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/live').read()" + +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--app-dir", "src"] \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index f84fd57d..4bd90ca9 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,9 +1,10 @@ -x-lab-number: 2 +x-lab-number: 3 x-required-roles: - api - postgres + - load_balancer -# Лабораторная 2. API + PostgreSQL + Redis +# Лабораторная 3. LB + 2 API-реплики + PostgreSQL + Redis. services: postgres: image: postgres:18.6-alpine @@ -26,8 +27,6 @@ services: image: redis:7.4.1-alpine container_name: mtuci-redis command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--save", "60", "1"] - ports: - - "127.0.0.1:6379:6379" volumes: - redis-data:/data healthcheck: @@ -40,10 +39,9 @@ services: api: build: . - image: mtuci-messenger:lab2 - container_name: mtuci-messenger-lab2 - ports: - - "127.0.0.1:8080:8080" + image: mtuci-messenger:lab3 + # НЕТ container_name: нужно масштабирование (--scale api=2). + # НЕТ ports: реплики не публикуют порт наружу — только через LB. env_file: - .env depends_on: @@ -53,18 +51,36 @@ services: condition: service_healthy healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"] - interval: 10s + interval: 5s timeout: 3s retries: 5 start_period: 10s restart: unless-stopped + deploy: + replicas: 2 + resources: + limits: + cpus: "1.0" + memory: 512M + + lb: + image: nginx:1.27.3-alpine + container_name: mtuci-lb + ports: + - "127.0.0.1:8080:80" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + api: + condition: service_healthy + restart: unless-stopped volumes: postgres-data: - name: mtuci2026lab2_postgres-data + name: mtuci2026lab3_postgres-data redis-data: - name: mtuci2026lab2_redis-data + name: mtuci2026lab3_redis-data networks: default: - name: mtuci2026lab2_default \ No newline at end of file + name: mtuci2026lab3_default \ No newline at end of file diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..98be36f4 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,38 @@ +worker_processes auto; +events { worker_connections 1024; } + +http { + # access_log / error_log по умолчанию в stdout/stderr образа nginx. + + upstream api_backend { + # Docker DNS отдаёт все IP реплик сервиса api. + server api:8080 max_fails=2 fail_timeout=5s; + keepalive 32; + } + + server { + listen 80; + + # Короткие таймауты, чтобы мёртвый backend быстро исключался. + proxy_connect_timeout 2s; + proxy_send_timeout 10s; + proxy_read_timeout 10s; + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + + # readiness LB напрямую проверяет свой upstream через api (docker healthcheck). + location = /lb/health { + return 200 "ok\n"; + add_header Content-Type text/plain; + } + } +} \ No newline at end of file diff --git a/src/app/api/messages.py b/src/app/api/messages.py index d6350726..33c26786 100644 --- a/src/app/api/messages.py +++ b/src/app/api/messages.py @@ -1,8 +1,10 @@ import base64 +import hashlib import json +import time from datetime import datetime from uuid import UUID -from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi import APIRouter, Depends, Header, HTTPException, Query from ..models.schemas import CreateMessage, Message, MessagePage, User from ..storage.postgres import storage from .security import current_user @@ -33,6 +35,17 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple: raise HTTPException(status_code=400, detail="invalid_request") +def _canonical_body_hash(payload: CreateMessage) -> str: + """sha256 канонизированного JSON. Отсутствующий attachment_ids == []. + Порядок ключей не важен (sort_keys). Это ровно то, что требует контракт: + 'порядок ключей JSON и отсутствующий attachment_ids вместо [] семантически равны'. + """ + data = payload.model_dump(exclude_none=True) + data.setdefault("attachment_ids", []) + canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + @router.post( path="/{chat_id}/messages", summary="Отправить сообщение в чат", @@ -43,11 +56,53 @@ def create_message( chat_id: UUID, payload: CreateMessage, user: User = Depends(current_user), + idempotency_key: str = Header(..., alias="Idempotency-Key"), ) -> Message: + # Контракт: ключ ASCII [A-Za-z0-9._:-]{1,128}. + if not (1 <= len(idempotency_key) <= 128): + raise HTTPException(status_code=400, detail="invalid_request") + if not all(c.isalnum() or c in "._:-" for c in idempotency_key): + raise HTTPException(status_code=400, detail="invalid_request") + _require_member(chat_id, user.id) if not payload.text.strip(): raise HTTPException(status_code=400, detail="invalid_request") - return storage.add_message(chat_id, user.id, payload.text) + + method = "POST" + path = "/api/v1/chats/%s/messages" % chat_id + body_hash = _canonical_body_hash(payload) + + # 1) Атомарно бронируем ключ. Ровно один поток (или реплика) получит + # право создать сообщение, остальные уйдут в replay. + while True: + state, info = storage.reserve_idempotency( + user.id, method, path, idempotency_key, body_hash + ) + if state == "reserved": + break + if state == "retry": + time.sleep(0.05) + continue + # state == "replay" + if info["body_hash"] != body_hash: + raise HTTPException(status_code=409, detail="conflict") + if info["response_status"] == 0: + # Победитель ещё не записал финальный ответ — ждём. + time.sleep(0.05) + continue + return Message.model_validate(info["response_body"]) + + # 2) Мы выиграли гонку: создаём сообщение и фиксируем результат. + message = storage.add_message(chat_id, user.id, payload.text) + storage.complete_idempotency( + user_id=user.id, + method=method, + path=path, + key=idempotency_key, + response_status=201, + response_body=json.loads(message.model_dump_json()), + ) + return message @router.get( @@ -61,7 +116,7 @@ def list_messages( limit: int = Query(50, ge=1, le=100), cursor: str | None = None, ) -> MessagePage: - """Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории.""" + """Keyset-пагинация в SQL: (created_at, id) по возрастанию""" _require_member(chat_id, user.id) after = _decode_cursor(chat_id, cursor) if cursor else None # Берём limit+1, чтобы понять, есть ли следующая страница diff --git a/src/app/main.py b/src/app/main.py index d4eea528..a0c63d3c 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -24,24 +24,29 @@ logging.basicConfig( ) logger = logging.getLogger("app") +# X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит +# из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз. +INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12] + @asynccontextmanager async def lifespan(app: FastAPI): init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4) init_schema() # создать таблицы в БД если их ещё нет logger.info( - "event=startup app_env=%s session_store=%s", + "event=startup app_env=%s session_store=%s instance_id=%s", os.environ.get("APP_ENV", "lab"), os.environ.get("SESSION_STORE", "postgres"), + INSTANCE_ID, ) yield close_pool() - logger.info("event=shutdown_complete") + logger.info("event=shutdown_complete instance_id=%s", INSTANCE_ID) app = FastAPI( - title="MTUCI Messenger — lab2", - version="1.2.0", + title="MTUCI Messenger — lab3", + version="1.3.0", lifespan=lifespan, swagger_ui_parameters={"persistAuthorization": True}, ) @@ -60,22 +65,23 @@ app.openapi = custom_openapi @app.middleware("http") async def observability_middleware(request: Request, call_next): - """X-Request-Id во всех ответах + структурный лог без тела сообщений.""" + """X-Request-Id и X-Instance-Id во всех ответах + структурный лог.""" request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex request.state.request_id = request_id started = time.monotonic() response = await call_next(request) response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID duration_ms = round((time.monotonic() - started) * 1000, 2) - # Логируем только метаданные: метод, путь без query, статус, длительность, request_id path = request.url.path logger.info( - "event=http method=%s path=%s status=%s duration_ms=%s request_id=%s", + "event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s", request.method, path, response.status_code, duration_ms, request_id, + INSTANCE_ID, ) return response @@ -108,6 +114,8 @@ def _error_response( headers = {} if status_code == 401: headers["WWW-Authenticate"] = _unauthorized_challenge(path) + # X-Instance-Id может не быть при ошибке до middleware — но middleware + # оборачивает всё, так что заголовок будет добавлен в middleware. return JSONResponse( status_code=status_code, content={"error": {"code": code, "message": message, "request_id": request_id}}, @@ -142,12 +150,7 @@ async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError @app.exception_handler(RuntimeError) async def runtime_error_handler(request: Request, exc: RuntimeError): - """Redis недоступен или конфигурация битая. - - sessions.py поднимает RuntimeError("redis_unavailable") при ошибке Redis. - Отдаём 503, чтобы смоук/resilience видели корректный unavailable, - а не внутреннюю 500. - """ + """Redis недоступен или конфигурация битая.""" request_id = getattr(request.state, "request_id", uuid.uuid4().hex) text = str(exc) if "redis_unavailable" in text: @@ -164,7 +167,6 @@ async def runtime_error_handler(request: Request, exc: RuntimeError): @app.exception_handler(Exception) async def unhandled_exception_handler(request: Request, exc: Exception): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) - # Внутренние детали не раскрываем; пишем в лог без секретов logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id) return _error_response(500, "Внутренняя ошибка", request_id, request.url.path) @@ -186,11 +188,7 @@ if __name__ == "__main__": server = uvicorn.Server(config) def _handle_sigterm(signum, frame): - """SIGTERM: логируем и инициируем graceful shutdown uvicorn. - - server.should_exit=True заставляет uvicorn закрыть слушающий сокет - (healthcheck перестаёт отвечать) и корректно завершить процесс. - """ + """SIGTERM: логируем и инициируем graceful shutdown uvicorn.""" logger.info("event=sigterm_received signal=%s", signum) server.should_exit = True diff --git a/src/app/storage/db.py b/src/app/storage/db.py index 4dbaabb2..1beb6fcb 100644 --- a/src/app/storage/db.py +++ b/src/app/storage/db.py @@ -86,6 +86,24 @@ CREATE TABLE IF NOT EXISTS sessions ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at TIMESTAMPTZ NOT NULL ); + +-- lab3: общая идемпотентность POST /messages. +-- scope: user_id + method + path + key (см. contracts/README.md). +-- body_hash — sha256 канонизированного JSON без attachment_ids=[], чтобы +-- отличать повтор «того же» body (201, тот же Message) от «другого» (409). +CREATE TABLE IF NOT EXISTS idempotency_keys ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method TEXT NOT NULL, + path TEXT NOT NULL, + key TEXT NOT NULL, + body_hash TEXT NOT NULL, + response_status INT NOT NULL, + response_body JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, method, path, key) +); +CREATE INDEX IF NOT EXISTS idx_idempotency_created + ON idempotency_keys (created_at); """ diff --git a/src/app/storage/postgres.py b/src/app/storage/postgres.py index 114bf96e..2af35e74 100644 --- a/src/app/storage/postgres.py +++ b/src/app/storage/postgres.py @@ -263,5 +263,73 @@ class PostgresStorage: ) return [_row_to_message(r) for r in cur.fetchall()] + # ---------- Идемпотентность (lab3) ---------- + def reserve_idempotency( + self, user_id: UUID, method: str, path: str, key: str, body_hash: str + ) -> tuple[str, Optional[dict]]: + """Атомарно бронирует ключ идемпотентности. + + Возвращает ('reserved', None) если мы выиграли гонку и должны + выполнить операцию и затем вызвать complete_idempotency(...). + + Возвращает ('replay', {...}) если ключ уже занят — возвращаем + сохранённый ранее ответ (или 409, если body_hash не совпадает). + + Делается одним INSERT ... ON CONFLICT DO NOTHING RETURNING, чтобы + при одновременных запросах через разные реплики ровно один поток + получил право создать сообщение. + """ + with connection() as conn, conn.cursor() as cur: + cur.execute( + "INSERT INTO idempotency_keys" + " (user_id, method, path, key, body_hash, response_status, response_body)" + " VALUES (%s, %s, %s, %s, %s, 0, '{}'::jsonb)" + " ON CONFLICT (user_id, method, path, key) DO NOTHING" + " RETURNING key", + (user_id, method, path, key, body_hash), + ) + won = cur.fetchone() is not None + conn.commit() + + if won: + return ("reserved", None) + + # Кто-то уже занял ключ. Читаем строку и проверяем body_hash. + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT body_hash, response_status, response_body" + " FROM idempotency_keys" + " WHERE user_id = %s AND method = %s AND path = %s AND key = %s", + (user_id, method, path, key), + ) + row = cur.fetchone() + if row is None: + # Странно: только что был конфликт, а строки нет. Повторяем. + return ("retry", None) + return ( + "replay", + { + "body_hash": row[0], + "response_status": row[1], + "response_body": row[2], + }, + ) + + def complete_idempotency( + self, user_id: UUID, method: str, path: str, key: str, + response_status: int, response_body: dict, + ) -> None: + """Заполняет ранее забронированную строку реальным ответом.""" + import json as _json + with connection() as conn, conn.cursor() as cur: + cur.execute( + "UPDATE idempotency_keys" + " SET response_status = %s, response_body = %s" + " WHERE user_id = %s AND method = %s AND path = %s AND key = %s", + (response_status, _json.dumps(response_body), + user_id, method, path, key), + ) + conn.commit() + storage = PostgresStorage() # единственный экземпляр на процесс \ No newline at end of file