import base64 import binascii from datetime import datetime, timezone from uuid import UUID, uuid4 import asyncpg from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response from pydantic import BaseModel, ConfigDict, Field from . import cache, db, rediscli, sessions from .cursors import decode_cursor, encode_cursor from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError from .config import settings from .passwords import dummy_hash, hash_password, verify_password from .serialize import chat_json, message_json, user_json from .timeutil import fmt_dt api = APIRouter() health = APIRouter() class CreateUser(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 CreateChat(BaseModel): model_config = ConfigDict(extra="forbid") title: str = Field(min_length=1, max_length=100) member_ids: list[UUID] = Field(min_length=1, max_length=100) class CreateMessage(BaseModel): model_config = ConfigDict(extra="forbid") text: str = Field(min_length=1, max_length=4000) def _blank(value: str) -> bool: return value.strip() == "" def _limit(raw: str | None) -> int: if raw is None or raw == "": return 50 try: value = int(raw) except ValueError: raise AppError(400, "invalid_request", "Некорректный limit") from None if value < 1 or value > 100: raise AppError(400, "invalid_request", "Некорректный limit") return value async def current_user(request: Request) -> asyncpg.Record: header = request.headers.get("Authorization") or "" scheme, _, rest = header.partition(" ") if scheme.lower() != "bearer" or not rest.strip(): raise AppError(401, "unauthorized", "Требуется аутентификация", BEARER_CHALLENGE) user_id = await sessions.resolve(rest.strip()) row = await db.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id) if row is None: raise AppError(401, "unauthorized", "Требуется аутентификация", BEARER_CHALLENGE) return row async def member_ids_of(chat_id: UUID) -> list[UUID]: rows = await db.fetch("SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id) return [r["user_id"] for r in rows] async def load_chat_for_member(chat_id: UUID, user_id: UUID) -> asyncpg.Record: row = await db.fetchrow( """ SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $2 WHERE c.id = $1 """, chat_id, user_id, ) if row is None: raise AppError(404, "not_found", "Объект не найден") return row @health.get("/health/live") async def live() -> JSONResponse: return JSONResponse({"status": "ok"}) @health.get("/health/ready") async def ready() -> JSONResponse: await db.ping() await rediscli.ping() return JSONResponse({"status": "ok"}) @api.post("/users") async def register(body: CreateUser) -> JSONResponse: if _blank(body.display_name) or _blank(body.password) or _blank(body.username): raise AppError(400, "invalid_request", "Некорректные поля") user_id = uuid4() created = datetime.now(timezone.utc) try: await db.execute( """ INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5) """, user_id, body.username, body.display_name, hash_password(body.password), created, ) except asyncpg.UniqueViolationError: raise AppError(409, "conflict", "Имя пользователя занято") from None except AppError: raise except Exception: raise AppError(503, "unavailable", "Сервис временно недоступен") from None return JSONResponse( user_json({"id": user_id, "username": body.username, "display_name": body.display_name, "created_at": created}), status_code=201, ) @api.get("/users/me") async def me(request: Request) -> JSONResponse: row = await current_user(request) return JSONResponse(user_json(row)) @api.post("/auth/sessions") async def login(request: Request) -> JSONResponse: header = request.headers.get("Authorization") or "" scheme, _, rest = header.partition(" ") if scheme.lower() != "basic" or not rest.strip(): raise AppError(401, "unauthorized", "Требуется аутентификация", BASIC_CHALLENGE) try: decoded = base64.b64decode(rest.strip(), validate=True).decode("utf-8") except (binascii.Error, UnicodeError, ValueError): raise AppError(401, "unauthorized", "Требуется аутентификация", BASIC_CHALLENGE) from None username, sep, password = decoded.partition(":") if not sep: raise AppError(401, "unauthorized", "Требуется аутентификация", BASIC_CHALLENGE) row = await db.fetchrow( "SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username, ) password_hash = row["password_hash"] if row else dummy_hash() if row is None or not verify_password(password_hash, password): raise AppError(401, "unauthorized", "Требуется аутентификация", BASIC_CHALLENGE) token, expires_at = await sessions.create(row["id"]) return JSONResponse( { "token": token, "token_type": "Bearer", "expires_at": expires_at, "user": user_json(row), }, status_code=201, ) @api.delete("/auth/sessions/current") async def logout(request: Request) -> Response: header = request.headers.get("Authorization") or "" scheme, _, rest = header.partition(" ") if scheme.lower() != "bearer" or not rest.strip(): raise AppError(401, "unauthorized", "Требуется аутентификация", BEARER_CHALLENGE) await sessions.revoke(rest.strip()) return Response(status_code=204) @api.post("/chats") async def create_chat(request: Request, body: CreateChat) -> JSONResponse: if _blank(body.title): raise AppError(400, "invalid_request", "Некорректные поля") if len(body.member_ids) != len(set(body.member_ids)): raise AppError(400, "invalid_request", "Некорректный список участников") user = await current_user(request) if user["id"] not in body.member_ids: raise AppError(400, "invalid_request", "Некорректный список участников") chat_id = uuid4() created = datetime.now(timezone.utc) try: async with db.require_pool().acquire() as conn: async with conn.transaction(): existing = await conn.fetch("SELECT id FROM users WHERE id = ANY($1::uuid[])", body.member_ids) if len(existing) != len(body.member_ids): raise AppError(400, "invalid_request", "Некорректный список участников") await conn.execute( "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", chat_id, body.title, created, ) await conn.executemany( "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(chat_id, mid) for mid in body.member_ids], ) except AppError: raise except Exception: raise AppError(503, "unavailable", "Сервис временно недоступен") from None return JSONResponse(chat_json({"id": chat_id, "title": body.title, "created_at": created}, body.member_ids), status_code=201) @api.get("/chats") async def list_chats(request: Request) -> JSONResponse: user = await current_user(request) limit = _limit(request.query_params.get("limit")) cursor = request.query_params.get("cursor") args: list = [user["id"]] clause = "" if cursor: data = decode_cursor(cursor, "chat") clause = "AND (c.created_at, c.id) > ($2, $3)" args.extend([datetime.fromisoformat(data["t"].replace("Z", "+00:00")), UUID(data["i"])]) rows = await db.fetch( f""" SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 WHERE 1=1 {clause} ORDER BY c.created_at, c.id LIMIT {limit + 1} """, *args, ) page = rows[:limit] items = [] for row in page: items.append(chat_json(row, await member_ids_of(row["id"]))) next_cursor = None if len(rows) > limit: last = page[-1] next_cursor = encode_cursor({"k": "chat", "t": fmt_dt(last["created_at"]), "i": str(last["id"])}) return JSONResponse({"items": items, "next_cursor": next_cursor}) @api.get("/chats/{chat_id}") async def get_chat(request: Request, chat_id: UUID) -> JSONResponse: user = await current_user(request) row = await load_chat_for_member(chat_id, user["id"]) return JSONResponse(chat_json(row, await member_ids_of(chat_id))) async def _load_messages(chat_id: UUID, after_ts: datetime | None, after_id: UUID | None, limit: int) -> dict: await cache.incr_history_sql() if after_ts is None: rows = await db.fetch( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2 """, chat_id, limit + 1, ) else: rows = await db.fetch( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4 """, chat_id, after_ts, after_id, limit + 1, ) page = rows[:limit] items = [message_json(r) for r in page] next_cursor = None if len(rows) > limit: last = page[-1] next_cursor = encode_cursor( {"k": "msg", "c": str(chat_id), "t": fmt_dt(last["created_at"]), "i": str(last["id"])} ) return {"items": items, "next_cursor": next_cursor} @api.post("/chats/{chat_id}/messages") async def create_message(request: Request, chat_id: UUID, body: CreateMessage) -> JSONResponse: if _blank(body.text): raise AppError(400, "invalid_request", "Некорректные поля") user = await current_user(request) await load_chat_for_member(chat_id, user["id"]) message_id = uuid4() created = datetime.now(timezone.utc) try: await db.execute( """ INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5) """, message_id, chat_id, user["id"], body.text, created, ) except AppError: raise except Exception: raise AppError(503, "unavailable", "Сервис временно недоступен") from None await cache.invalidate_history(str(chat_id)) return JSONResponse( message_json( { "id": message_id, "chat_id": chat_id, "sender_id": user["id"], "text": body.text, "created_at": created, } ), status_code=201, ) @api.get("/chats/{chat_id}/messages") async def list_messages(request: Request, chat_id: UUID) -> JSONResponse: user = await current_user(request) await load_chat_for_member(chat_id, user["id"]) limit = _limit(request.query_params.get("limit")) cursor = request.query_params.get("cursor") or "" after_ts = after_id = None if cursor: data = decode_cursor(cursor, "msg", str(chat_id)) after_ts = datetime.fromisoformat(data["t"].replace("Z", "+00:00")) after_id = UUID(data["i"]) async def loader(): return await _load_messages(chat_id, after_ts, after_id, limit) page = await cache.get_history_page(str(chat_id), cursor, limit, loader) return JSONResponse(page) class LabFlags(BaseModel): model_config = ConfigDict(extra="forbid") singleflight: bool | None = None invalidate: bool | None = None reset_sql: bool | None = None @api.get("/_lab/metrics") async def lab_metrics() -> JSONResponse: if not settings.lab_mode: raise AppError(404, "not_found", "Объект не найден") return JSONResponse( { "singleflight": await cache.singleflight_enabled(), "invalidate": await cache.invalidate_enabled(), "history_sql": await cache.history_sql_count(), } ) @api.post("/_lab/flags") async def lab_flags(body: LabFlags) -> JSONResponse: if not settings.lab_mode: raise AppError(404, "not_found", "Объект не найден") if body.reset_sql: await cache.reset_history_sql_count() flags = await cache.set_flags(singleflight=body.singleflight, invalidate=body.invalidate) return JSONResponse(flags)