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 }