From 17377031cc2854fa6379f926e6be13836d1dd3ee Mon Sep 17 00:00:00 2001 From: Amin Kazakov Date: Fri, 23 Oct 2026 01:32:02 +0300 Subject: [PATCH] =?UTF-8?q?=D1=81=D1=85=D0=B5=D0=BC=D0=B0=20=D0=B1=D0=B4?= =?UTF-8?q?=20=D0=B8=20=D0=BA=D0=BE=D0=BC=D0=BF=D0=BE=D1=83=D0=B7=20=D1=81?= =?UTF-8?q?=20=D0=BF=D0=BE=D1=81=D1=82=D0=B3=D1=80=D0=B5=D1=81=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 19 ++++ app.py | 242 ++++++++++++++++++++++++++++++++++++++++ compose.yaml | 18 +++ migrations/001_init.sql | 39 +++++++ requirements.txt | 6 + schemas.py | 40 +++++++ 6 files changed, 364 insertions(+) create mode 100644 Dockerfile create mode 100644 app.py create mode 100644 compose.yaml create mode 100644 migrations/001_init.sql create mode 100644 requirements.txt create mode 100644 schemas.py diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..a3af8cb5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM python:3.11.9-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY app.py schemas.py ./ + +# создать непривилегированного пользователя +RUN useradd --create-home --shell /bin/bash appuser +USER appuser + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready').read()" || exit 1 + +CMD ["sh", "-c", "exec uvicorn app:app --host 0.0.0.0 --port 8080"] \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 00000000..071bf80e --- /dev/null +++ b/app.py @@ -0,0 +1,242 @@ +import uuid +import threading +from datetime import datetime, timezone + +from fastapi import FastAPI, Header, HTTPException, Query, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +from schemas import ( + User, CreateUser, + Chat, CreateChat, ChatPage, + Message, CreateMessage, MessagePage, +) + +app = FastAPI() + +lock = threading.Lock() + +users: dict[str, dict] = {} +usernames: set[str] = set() +chats: dict[str, Chat] = {} +messages: dict[str, list[Message]] = {} + + +def now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def get_current_user(x_user_id: str | None): + if x_user_id is None: + raise HTTPException( + status_code=401, + detail="unauthorized", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + try: + uuid.UUID(x_user_id) + except ValueError: + raise HTTPException(status_code=400, detail="Invalid X-User-Id") + + user = users.get(x_user_id) + if user is None: + raise HTTPException( + status_code=401, + detail="unauthorized", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + return user + + +@app.middleware("http") +async def xri(request: Request, call_next): + rid = request.headers.get("X-Request-Id") or str(uuid.uuid4()) + request.state.request_id = rid + response = await call_next(request) + response.headers["X-Request-Id"] = rid + return response + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc: RequestValidationError): + return JSONResponse( + status_code=400, + content={ + "error": { + "code": "invalid_request", + "message": "Invalid request body", + "request_id": request.state.request_id, + } + }, + ) + + +@app.exception_handler(StarletteHTTPException) +async def http_exception_handler(request: Request, exc: StarletteHTTPException): + codes = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + } + code = codes.get(exc.status_code, "internal_error") + return JSONResponse( + status_code=exc.status_code, + content={ + "error": { + "code": code, + "message": str(exc.detail), + "request_id": request.state.request_id, + } + }, + headers=exc.headers or {}, + ) + + +@app.get("/health/live") +async def liveness(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def readiness(): + return {"status": "ok"} + + +@app.post("/api/v1/users", status_code=201) +async def registerUser(payload: CreateUser): + uid = str(uuid.uuid4()) + user = User( + id=uid, + username=payload.username, + display_name=payload.display_name, + created_at=now_iso(), + ) + with lock: + if payload.username in usernames: + raise HTTPException(status_code=409, detail="Username already exists") + usernames.add(payload.username) + users[uid] = user + return user + + +@app.get("/api/v1/users/me") +async def currentUser(x_user_id: str | None = Header(default=None)): + return get_current_user(x_user_id) + + +@app.post("/api/v1/chats", status_code=201) +async def createChat(payload: CreateChat, x_user_id: str | None = Header(default=None)): + me = get_current_user(x_user_id) + + if len(set(payload.member_ids)) != len(payload.member_ids): + raise HTTPException(status_code=400, detail="member_ids must be unique") + + for i in payload.member_ids: + try: + uuid.UUID(i) + except ValueError: + raise HTTPException(status_code=400, detail="Invalid member id") + if i not in users: + raise HTTPException(status_code=400, detail="Unknown member") + + if me.id not in payload.member_ids: + raise HTTPException(status_code=400, detail="Caller must be a member") + + cid = str(uuid.uuid4()) + chat = Chat( + id=cid, + title=payload.title, + member_ids=payload.member_ids, + created_at=now_iso(), + ) + with lock: + chats[cid] = chat + messages[cid] = [] + return chat + + +@app.get("/api/v1/chats") +async def listChats( + x_user_id: str | None = Header(default=None), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), +): + me = get_current_user(x_user_id) + with lock: + mine = [c for c in chats.values() if me.id in c.member_ids] + mine.sort(key=lambda c: (c.created_at, c.id)) + + if cursor is not None: + ids = [c.id for c in mine] + if cursor not in ids: + raise HTTPException(status_code=400, detail="Invalid cursor") + idx = ids.index(cursor) + mine = mine[idx + 1:] + + page = mine[:limit] + next_cursor = page[-1].id if len(mine) > limit else None + return ChatPage(items=page, next_cursor=next_cursor) + + +@app.get("/api/v1/chats/{chat_id}") +async def getChat(chat_id: str, x_user_id: str | None = Header(default=None)): + me = get_current_user(x_user_id) + with lock: + chat = chats.get(chat_id) + if chat is None or me.id not in chat.member_ids: + raise HTTPException(status_code=404, detail="Chat not found") + return chat + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +async def createMessage( + chat_id: str, + payload: CreateMessage, + x_user_id: str | None = Header(default=None), +): + me = get_current_user(x_user_id) + with lock: + chat = chats.get(chat_id) + if chat is None or me.id not in chat.member_ids: + raise HTTPException(status_code=404, detail="Chat not found") + + msg = Message( + id=str(uuid.uuid4()), + chat_id=chat_id, + sender_id=me.id, + text=payload.text, + created_at=now_iso(), + ) + messages.setdefault(chat_id, []).append(msg) + return msg + + +@app.get("/api/v1/chats/{chat_id}/messages") +async def listMessages( + chat_id: str, + x_user_id: str | None = Header(default=None), + limit: int = Query(default=50, ge=1, le=100), + cursor: str | None = Query(default=None, min_length=1), +): + me = get_current_user(x_user_id) + with lock: + chat = chats.get(chat_id) + if chat is None or me.id not in chat.member_ids: + raise HTTPException(status_code=404, detail="Chat not found") + msgs = list(messages.get(chat_id, [])) + + msgs.sort(key=lambda m: (m.created_at, m.id)) + + if cursor is not None: + ids = [m.id for m in msgs] + if cursor not in ids: + raise HTTPException(status_code=400, detail="Invalid cursor") + idx = ids.index(cursor) + msgs = msgs[idx + 1:] + + page = msgs[:limit] + next_cursor = page[-1].id if len(msgs) > limit else None + return MessagePage(items=page, next_cursor=next_cursor) \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..ee53aba2 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,18 @@ +services: + postgres: + image: postgres:17.6-alpine + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_DB: ${POSTGRES_DB} + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] + interval: 5s + timeout: 3s + retries: 10 +volumes: + pgdata: \ No newline at end of file diff --git a/migrations/001_init.sql b/migrations/001_init.sql new file mode 100644 index 00000000..c2507900 --- /dev/null +++ b/migrations/001_init.sql @@ -0,0 +1,39 @@ +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id), + user_id UUID NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id), + sender_id UUID NOT NULL REFERENCES users(id), + text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE sessions ( + token_hash TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ +); + +CREATE INDEX messages_chat_created_idx ON messages (chat_id, created_at, id); +CREATE INDEX chat_members_user_idx ON chat_members (user_id); +CREATE INDEX sessions_user_idx ON sessions (user_id); \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..3b6c1d6a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +fastapi +uvicorn[standard] +psycopg[binary] +psycopg_pool +argon2-cffi +redis \ No newline at end of file diff --git a/schemas.py b/schemas.py new file mode 100644 index 00000000..ecb9b7c1 --- /dev/null +++ b/schemas.py @@ -0,0 +1,40 @@ +from pydantic import BaseModel, Field +import uuid + +class User(BaseModel): + id: str + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + created_at: str + +class CreateUser(BaseModel): + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + +class Chat(BaseModel): + id: str + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + created_at: str + +class CreateChat(BaseModel): + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + +class ChatPage(BaseModel): + items: list[Chat] + next_cursor: str | None + +class CreateMessage(BaseModel): + text: str = Field(min_length=1, max_length=4000) + +class Message(BaseModel): + id: str + chat_id: str + sender_id: str + text: str = Field(min_length=1, max_length=4000) + created_at: str + +class MessagePage(BaseModel): + items: list[Message] + next_cursor: str | None