From fc62d81ec4ff5e80b1dfc8ff4d494fd43b79b893 Mon Sep 17 00:00:00 2001 From: caramelteawithmint <146834163+caramelteawithmint@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:13:43 +0300 Subject: [PATCH] 3_grade --- Dockerfile | 18 +++ app/__init__.py | 0 app/config.py | 11 ++ app/database.py | 11 ++ app/main.py | 307 ++++++++++++++++++++++++++++++++++++++++++++ app/models.py | 48 +++++++ app/schemas.py | 48 +++++++ app/security.py | 17 +++ compose.yaml | 29 +++++ requirements.txt | 9 ++ scripts/restart.bat | 2 + scripts/restart.sh | 3 + 12 files changed, 503 insertions(+) create mode 100644 Dockerfile create mode 100644 app/__init__.py create mode 100644 app/config.py create mode 100644 app/database.py create mode 100644 app/main.py create mode 100644 app/models.py create mode 100644 app/schemas.py create mode 100644 app/security.py create mode 100644 compose.yaml create mode 100644 requirements.txt create mode 100644 scripts/restart.bat create mode 100644 scripts/restart.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..cf681917 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.11-slim + +WORKDIR /app + +# Устанавливаем системные зависимости для сборки psycopg/asyncpg +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +# Копируем зависимости и устанавливаем их +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Копируем весь остальной код (папку app и т.д.) +COPY . . + +# Запускаем FastAPI через uvicorn +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"] \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..00f353db --- /dev/null +++ b/app/config.py @@ -0,0 +1,11 @@ +from pydantic_settings import BaseSettings + +class Settings(BaseSettings): + database_url: str = "postgresql+asyncpg://postgres:postgres@db:5432/messenger" + session_ttl_seconds: int = 3600 + instance_id: str = "api-node-1" + + class Config: + env_file = ".env" + +settings = Settings() \ No newline at end of file diff --git a/app/database.py b/app/database.py new file mode 100644 index 00000000..0fbcc725 --- /dev/null +++ b/app/database.py @@ -0,0 +1,11 @@ +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession +from sqlalchemy.orm import declarative_base +from app.config import settings + +engine = create_async_engine(settings.database_url, echo=False) +async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) +Base = declarative_base() + +async def get_db(): + async with async_session() as session: + yield session \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..3166e752 --- /dev/null +++ b/app/main.py @@ -0,0 +1,307 @@ +import uuid +import base64 +from datetime import datetime, timezone, timedelta +from typing import Optional +from fastapi import FastAPI, Request, Depends, HTTPException, status, Response +from fastapi.responses import JSONResponse +from fastapi.exceptions import RequestValidationError +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from sqlalchemy import delete + +from app.config import settings +from app.database import get_db, engine, Base +from app.models import User, Session, Chat, ChatMember, Message +from app.schemas import UserCreate, UserOut, SessionOut, ChatCreate, ChatOut, MessageCreate, MessageOut, MessagePage +from app import security + +app = FastAPI() + +# ---------- Middleware (X-Request-Id и X-Instance-Id) ---------- + +@app.middleware("http") +async def add_headers(request: Request, call_next): + request_id = str(uuid.uuid4()) + request.state.request_id = request_id + + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = settings.instance_id + return response + +# ---------- Обработчики ошибок (Контракт) ---------- + +def make_error_response(status_code: int, code: str, message: str, request_id: str, headers: dict = None): + return JSONResponse( + status_code=status_code, + content={"error": {"code": code, "message": message, "request_id": request_id}}, + headers=headers or {} + ) + +@app.exception_handler(HTTPException) +async def http_exception_handler(request: Request, exc: HTTPException): + req_id = getattr(request.state, "request_id", "unknown") + code_map = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + 413: "payload_too_large", + 415: "unsupported_media_type", + 429: "rate_limited", + 503: "unavailable", + 500: "internal_error" + } + code = code_map.get(exc.status_code, "internal_error") + return make_error_response(exc.status_code, code, str(exc.detail), req_id, exc.headers) + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler(request: Request, exc: RequestValidationError): + req_id = getattr(request.state, "request_id", "unknown") + return make_error_response(400, "invalid_request", "Validation error", req_id) + +@app.on_event("startup") +async def startup(): + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + +# ---------- Зависимости (Auth) ---------- + +security_scheme = HTTPBearer(auto_error=False) + +async def get_current_user( + credentials: HTTPAuthorizationCredentials = Depends(security_scheme), + db: AsyncSession = Depends(get_db) +) -> User: + if not credentials or credentials.scheme.lower() != "bearer": + raise HTTPException( + status_code=401, + detail="Not authenticated", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'} + ) + + token_hash = security.hash_token(credentials.credentials) + stmt = select(Session).where(Session.token_hash == token_hash) + result = await db.execute(stmt) + session = result.scalars().first() + + if not session or session.expires_at < datetime.now(timezone.utc): + raise HTTPException( + status_code=401, + detail="Session expired or invalid", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'} + ) + + stmt = select(User).where(User.id == session.user_id) + result = await db.execute(stmt) + user = result.scalars().first() + if not user: + raise HTTPException(status_code=401, detail="User not found", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + return user + +# ---------- API Эндпоинты ---------- + +@app.get("/health/live") +async def health_live(): + return {"status": "ok"} + +@app.get("/health/ready") +async def health_ready(): + return {"status": "ok"} + +@app.post("/api/v1/users", response_model=UserOut, status_code=201) +async def register_user(user_in: UserCreate, db: AsyncSession = Depends(get_db)): + if not user_in.display_name.strip() or not user_in.username.strip(): + raise HTTPException(status_code=400, detail="Fields cannot be empty") + + stmt = select(User).where(User.username == user_in.username) + result = await db.execute(stmt) + if result.scalars().first(): + raise HTTPException(status_code=409, detail="Username already taken") + + hashed_pwd = security.get_password_hash(user_in.password) + new_user = User( + username=user_in.username, + display_name=user_in.display_name, + password_hash=hashed_pwd + ) + db.add(new_user) + await db.commit() + await db.refresh(new_user) + return new_user + +@app.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201) +async def create_session(request: Request, db: AsyncSession = Depends(get_db)): + auth_header = request.headers.get("Authorization") + if not auth_header or not auth_header.startswith("Basic "): + raise HTTPException(status_code=401, detail="Basic auth required", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}) + + try: + decoded = base64.b64decode(auth_header[6:]).decode("utf-8") + username, password = decoded.split(":", 1) + except Exception: + raise HTTPException(status_code=401, detail="Invalid Basic auth format", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}) + + stmt = select(User).where(User.username == username) + result = await db.execute(stmt) + user = result.scalars().first() + + if not user or not security.verify_password(password, user.password_hash): + raise HTTPException(status_code=401, detail="Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}) + + raw_token = security.generate_session_token() + token_hash = security.hash_token(raw_token) + expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.session_ttl_seconds) + + new_session = Session(user_id=user.id, token_hash=token_hash, expires_at=expires_at) + db.add(new_session) + await db.commit() + + return { + "token": raw_token, + "token_type": "Bearer", + "expires_at": expires_at, + "user": user + } + +@app.get("/api/v1/users/me", response_model=UserOut) +async def get_me(current_user: User = Depends(get_current_user)): + return current_user + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +async def logout(request: Request, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + auth_header = request.headers.get("Authorization") + token = auth_header.split(" ")[1] + token_hash = security.hash_token(token) + + stmt = delete(Session).where(Session.token_hash == token_hash) + await db.execute(stmt) + await db.commit() + return Response(status_code=204) + +@app.post("/api/v1/chats", response_model=ChatOut, status_code=201) +async def create_chat(chat_in: ChatCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + if current_user.id not in chat_in.member_ids: + raise HTTPException(status_code=400, detail="Creator must be a member") + if len(set(chat_in.member_ids)) != len(chat_in.member_ids): + raise HTTPException(status_code=400, detail="Duplicate member_ids") + + stmt = select(User.id).where(User.id.in_(chat_in.member_ids)) + result = await db.execute(stmt) + existing_ids = set(result.scalars().all()) + if existing_ids != set(chat_in.member_ids): + raise HTTPException(status_code=400, detail="One or more members do not exist") + + new_chat = Chat(title=chat_in.title) + db.add(new_chat) + await db.flush() + + for member_id in chat_in.member_ids: + db.add(ChatMember(chat_id=new_chat.id, user_id=member_id)) + + await db.commit() + await db.refresh(new_chat) + + return { + "id": new_chat.id, + "title": new_chat.title, + "member_ids": chat_in.member_ids, + "created_at": new_chat.created_at + } + +@app.get("/api/v1/chats", response_model=dict) +async def list_chats(limit: int = 50, cursor: Optional[str] = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + if limit < 1 or limit > 100: + raise HTTPException(status_code=400, detail="Limit must be between 1 and 100") + + stmt = select(Chat).join(ChatMember).where(ChatMember.user_id == current_user.id).order_by(Chat.created_at, Chat.id).limit(limit) + result = await db.execute(stmt) + chats = result.scalars().all() + + items = [] + for c in chats: + stmt_m = select(ChatMember.user_id).where(ChatMember.chat_id == c.id) + res_m = await db.execute(stmt_m) + member_ids = res_m.scalars().all() + items.append({ + "id": c.id, + "title": c.title, + "member_ids": member_ids, + "created_at": c.created_at + }) + return {"items": items, "next_cursor": None} + +@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201) +async def create_message(chat_id: uuid.UUID, msg_in: MessageCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + stmt = select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id) + result = await db.execute(stmt) + if not result.scalars().first(): + raise HTTPException(status_code=404, detail="Chat not found") + + if not msg_in.text.strip(): + raise HTTPException(status_code=400, detail="Text cannot be empty or whitespace") + + new_msg = Message(chat_id=chat_id, sender_id=current_user.id, text=msg_in.text) + db.add(new_msg) + await db.commit() + await db.refresh(new_msg) + return new_msg + +@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage) +async def list_messages(chat_id: uuid.UUID, limit: int = 50, cursor: Optional[str] = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + stmt = select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id) + result = await db.execute(stmt) + if not result.scalars().first(): + raise HTTPException(status_code=404, detail="Chat not found") + + if limit < 1 or limit > 100: + raise HTTPException(status_code=400, detail="Limit must be between 1 and 100") + + query = select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at, Message.id) + + if cursor: + try: + decoded = base64.b64decode(cursor).decode() + created_str, id_str = decoded.split("|") + c_dt = datetime.fromisoformat(created_str) + c_id = uuid.UUID(id_str) + query = query.where((Message.created_at > c_dt) | ((Message.created_at == c_dt) & (Message.id > c_id))) + except Exception: + raise HTTPException(status_code=400, detail="Invalid cursor") + + query = query.limit(limit + 1) + result = await db.execute(query) + messages = result.scalars().all() + + next_cursor = None + if len(messages) > limit: + last = messages[limit - 1] + messages = messages[:limit] + raw = f"{last.created_at.isoformat()}|{last.id}" + next_cursor = base64.b64encode(raw.encode()).decode() + + return {"items": messages, "next_cursor": next_cursor} + +@app.get("/api/v1/chats/{chat_id}", response_model=ChatOut) +async def get_chat(chat_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + stmt = select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id) + result = await db.execute(stmt) + if not result.scalars().first(): + raise HTTPException(status_code=404, detail="Chat not found") + + stmt = select(Chat).where(Chat.id == chat_id) + result = await db.execute(stmt) + chat = result.scalars().first() + + stmt_m = select(ChatMember.user_id).where(ChatMember.chat_id == chat_id) + res_m = await db.execute(stmt_m) + member_ids = res_m.scalars().all() + + return { + "id": chat.id, + "title": chat.title, + "member_ids": member_ids, + "created_at": chat.created_at + } \ No newline at end of file diff --git a/app/models.py b/app/models.py new file mode 100644 index 00000000..5ffd7fa3 --- /dev/null +++ b/app/models.py @@ -0,0 +1,48 @@ +import uuid +from datetime import datetime, timezone +from sqlalchemy import Column, String, DateTime, ForeignKey, Text, Index +from sqlalchemy.dialects.postgresql import UUID +from app.database import Base + +def utcnow(): + return datetime.now(timezone.utc) + +class User(Base): + __tablename__ = "users" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + username = Column(String(50), unique=True, nullable=False, index=True) + display_name = Column(String(100), nullable=False) + password_hash = Column(String(255), nullable=False) + created_at = Column(DateTime(timezone=True), default=utcnow, nullable=False) + +class Session(Base): + __tablename__ = "sessions" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + token_hash = Column(String(255), unique=True, nullable=False, index=True) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + expires_at = Column(DateTime(timezone=True), nullable=False) + created_at = Column(DateTime(timezone=True), default=utcnow, nullable=False) + +class Chat(Base): + __tablename__ = "chats" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + title = Column(String(255), nullable=False) + created_at = Column(DateTime(timezone=True), default=utcnow, nullable=False) + +class ChatMember(Base): + __tablename__ = "chat_members" + chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True) + joined_at = Column(DateTime(timezone=True), default=utcnow, nullable=False) + +class Message(Base): + __tablename__ = "messages" + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False) + sender_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + text = Column(Text, nullable=False) + created_at = Column(DateTime(timezone=True), default=utcnow, nullable=False) + + __table_args__ = ( + Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"), + ) \ No newline at end of file diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 00000000..62c908af --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,48 @@ +from pydantic import BaseModel, Field, ConfigDict +from uuid import UUID +from datetime import datetime +from typing import List, Optional + +class UserCreate(BaseModel): + 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 UserOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + id: UUID + username: str + display_name: str + created_at: datetime + +class SessionOut(BaseModel): + token: str + token_type: str + user: UserOut + expires_at: datetime + +class ChatCreate(BaseModel): + title: str = Field(..., min_length=1, max_length=100) + member_ids: List[UUID] = Field(..., min_items=1, max_items=100) + +class ChatOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + id: UUID + title: str + member_ids: List[UUID] + created_at: datetime + +class MessageCreate(BaseModel): + text: str = Field(..., max_length=4000) + +class MessageOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: datetime + +class MessagePage(BaseModel): + items: List[MessageOut] + next_cursor: Optional[str] = None \ No newline at end of file diff --git a/app/security.py b/app/security.py new file mode 100644 index 00000000..01c0fc81 --- /dev/null +++ b/app/security.py @@ -0,0 +1,17 @@ +import secrets +import hashlib +from passlib.context import CryptContext + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + +def generate_session_token() -> str: + return secrets.token_hex(32) + +def hash_token(token: str) -> str: + return hashlib.sha256(token.encode()).hexdigest() \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..85e481d0 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,29 @@ +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: messenger + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d messenger"] + interval: 5s + timeout: 5s + retries: 5 + + api: + build: . + ports: + - "8080:8080" + environment: + - DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/messenger + - SESSION_TTL_SECONDS=3600 + - INSTANCE_ID=api-node-1 + depends_on: + db: + condition: service_healthy + +volumes: + pgdata: \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..6f8503cf --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi>=0.110.0,<0.112.0 +uvicorn[standard]>=0.29.0 +sqlalchemy[asyncio]>=2.0.29 +asyncpg>=0.29.0 +alembic>=1.13.1 +passlib>=1.7.4 +bcrypt==4.0.1 +pydantic-settings>=2.2.1 +python-dotenv>=1.0.1 \ No newline at end of file diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 00000000..cc080443 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,2 @@ +@echo off +exit /b 0 \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..8f421270 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,3 @@ +#!/bin/sh +docker compose restart api +docker compose restart db \ No newline at end of file