From 4080e2110adcbb413ec296641f78bd86c1fbb2e8 Mon Sep 17 00:00:00 2001 From: Getlles Date: Thu, 5 Nov 2026 15:29:34 +0300 Subject: [PATCH] grade_3 --- .env.example | 1 + app.py | 521 ++++++++++++++++++++++++++++++++++---------- compose.yaml | 33 +++ migrations/init.sql | 38 ++++ requirements.txt | 4 +- scripts/restart.bat | 3 + scripts/restart.sh | 3 + 7 files changed, 491 insertions(+), 112 deletions(-) create mode 100644 compose.yaml create mode 100644 migrations/init.sql create mode 100644 scripts/restart.bat create mode 100644 scripts/restart.sh diff --git a/.env.example b/.env.example index 714c807..12a2ea3 100644 --- a/.env.example +++ b/.env.example @@ -9,3 +9,4 @@ DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url +POSTGRES_PASSWORD=ahahaha_change \ No newline at end of file diff --git a/app.py b/app.py index 1b06a99..1c725b1 100644 --- a/app.py +++ b/app.py @@ -1,69 +1,148 @@ +import os +import base64 +import secrets import uuid -from datetime import datetime, timezone -from typing import Dict, List, Optional +from datetime import datetime, timezone, timedelta +from typing import List, Optional from uuid import UUID + +import psycopg2 +import psycopg2.extras +import bcrypt from fastapi import FastAPI, Header, HTTPException, Query, Response, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel, Field, field_validator, ConfigDict -app = FastAPI(title="MTUSI Messenger — lab1", version="1.1.0") +app = FastAPI(title="MTUSI Messenger — lab2", version="1.2.0") -USERS: Dict[str, dict] = {} -CHATS: Dict[str, dict] = {} -MESSAGES: Dict[str, List[dict]] = {} +DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger") +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) + +def get_db_connection(): + conn = psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor) + return conn + +def init_db(): + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username VARCHAR(32) UNIQUE NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL + ); + CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL + ); + CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) + ); + CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID REFERENCES users(id) ON DELETE CASCADE, + text VARCHAR(4000) NOT NULL, + created_at TIMESTAMPTZ NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id); + CREATE TABLE IF NOT EXISTS sessions ( + token VARCHAR(128) PRIMARY KEY, + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL + ); + """) + conn.commit() + conn.close() + +@app.on_event("startup") +def startup_event(): + init_db() def generate_request_id() -> str: return uuid.uuid4().hex -def make_error_response(status_code: int, code: str, message: str, req_id: str) -> JSONResponse: +def make_error_response( + status_code: int, + code: str, + message: str, + req_id: str, + extra_headers: Optional[dict] = None, +) -> JSONResponse: + headers = {"X-Request-Id": req_id, "X-Instance-Id": "instance-1"} + if extra_headers: + headers.update(extra_headers) return JSONResponse( status_code=status_code, - headers={"X-Request-Id": req_id}, + headers=headers, content={ "error": { "code": code, "message": message, - "request_id": req_id + "request_id": req_id, } - } + }, ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): req_id = request.headers.get("X-Request-Id") or generate_request_id() - return make_error_response(400, "invalid_request", "Validation error in request body or parameters", req_id) + return make_error_response( + status_code=400, + code="invalid_request", + message="Validation error in request body or parameters", + req_id=req_id + ) @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): req_id = request.headers.get("X-Request-Id") or generate_request_id() + headers = {"X-Request-Id": req_id, "X-Instance-Id": "instance-1"} + if exc.headers: + headers.update(exc.headers) + detail = exc.detail if isinstance(detail, dict) and "error" in detail: detail["error"]["request_id"] = req_id - return JSONResponse( - status_code=exc.status_code, - headers={"X-Request-Id": req_id}, - content=detail - ) - + return JSONResponse(status_code=exc.status_code, headers=headers, content=detail) + 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" + 500: "internal_error", } - code = code_map.get(exc.status_code, "internal_error") - return make_error_response(exc.status_code, code, str(detail), req_id) + return JSONResponse( + status_code=exc.status_code, + headers=headers, + content={ + "error": { + "code": code_map.get(exc.status_code, "internal_error"), + "message": str(detail), + "request_id": req_id, + } + }, + ) 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) - @field_validator("display_name") + @field_validator("display_name", "password") def not_blank(cls, v): if not v.strip(): raise ValueError("Must not be blank") @@ -94,50 +173,190 @@ class CreateMessage(BaseModel): def health_live(response: Response): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id + response.headers["X-Instance-Id"] = "instance-1" return {"status": "ok"} @app.get("/health/ready") def health_ready(response: Response): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id + response.headers["X-Instance-Id"] = "instance-1" + try: + conn = get_db_connection() + conn.close() + except Exception: + raise HTTPException(status_code=503, detail="Database unavailable") return {"status": "ok"} @app.post("/api/v1/users", status_code=201) def register_user(body: CreateUser, response: Response): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id + response.headers["X-Instance-Id"] = "instance-1" - for u in USERS.values(): - if u["username"] == body.username: - raise HTTPException(status_code=409, detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}}) - + password_hash = bcrypt.hashpw(body.password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') user_id = str(uuid.uuid4()) - created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - user_obj = { + created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + conn = get_db_connection() + try: + with conn.cursor() as cur: + cur.execute( + "INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES (%s, %s, %s, %s, %s)", + (user_id, body.username, body.display_name, password_hash, created_at) + ) + conn.commit() + except psycopg2.errors.UniqueViolation: + conn.rollback() + raise HTTPException(status_code=409, detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}}) + finally: + conn.close() + + return { "id": user_id, "username": body.username, "display_name": body.display_name, "created_at": created_at } - USERS[user_id] = user_obj - return user_obj -def get_current_user(x_user_id: Optional[str] = Header(None)) -> dict: - if not x_user_id or x_user_id not in USERS: - raise HTTPException(status_code=401, detail="Invalid or missing user identification") - return USERS[x_user_id] +@app.post("/api/v1/auth/sessions", status_code=201) +def create_session(authorization: Optional[str] = Header(None), response: Response = None): + req_id = generate_request_id() + response.headers["X-Request-Id"] = req_id + response.headers["X-Instance-Id"] = "instance-1" + + if not authorization or not authorization.startswith("Basic "): + raise HTTPException( + status_code=401, + detail="Missing or invalid basic auth", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} + ) + + try: + encoded = authorization.split(" ")[1] + decoded = base64.b64decode(encoded).decode("utf-8") + username, password = decoded.split(":", 1) + except Exception: + raise HTTPException( + status_code=401, + detail="Invalid credentials format", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} + ) + + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute("SELECT * FROM users WHERE username = %s", (username,)) + user = cur.fetchone() + + if not user or not bcrypt.checkpw(password.encode('utf-8'), user['password_hash'].encode('utf-8')): + conn.close() + raise HTTPException( + status_code=401, + detail="Invalid credentials", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} + ) + + token = secrets.token_urlsafe(48) # >= 256 bits entropy + expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS) + expires_at_str = expires_at.isoformat().replace("+00:00", "Z") + created_at_str = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + with conn.cursor() as cur: + cur.execute( + "INSERT INTO sessions (token, user_id, expires_at, created_at) VALUES (%s, %s, %s, %s)", + (token, user['id'], expires_at_str, created_at_str) + ) + conn.commit() + conn.close() + + return { + "token": token, + "token_type": "Bearer", + "expires_at": expires_at_str, + "user": { + "id": user['id'], + "username": user['username'], + "display_name": user['display_name'], + "created_at": user['created_at'].isoformat().replace("+00:00", "Z") if isinstance(user['created_at'], datetime) else user['created_at'] + } + } + +def get_current_user_from_token(authorization: Optional[str] = Header(None)) -> dict: + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException( + status_code=401, + detail="Missing or invalid bearer token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'} + ) + token = authorization.split(" ")[1] + + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + SELECT u.*, s.expires_at FROM sessions s + JOIN users u ON s.user_id = u.id + WHERE s.token = %s + """, (token,)) + row = cur.fetchone() + conn.close() + + if not row: + raise HTTPException( + status_code=401, + detail="Invalid session token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'} + ) + + expires_at = row['expires_at'] + if isinstance(expires_at, str): + expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00")) + if expires_at < datetime.now(timezone.utc): + raise HTTPException( + status_code=401, + detail="Session expired", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'} + ) + + return { + "id": row['id'], + "username": row['username'], + "display_name": row['display_name'], + "created_at": row['created_at'].isoformat().replace("+00:00", "Z") if isinstance(row['created_at'], datetime) else row['created_at'] + } + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def revoke_session(response: Response, authorization: Optional[str] = Header(None)): + req_id = generate_request_id() + + user = get_current_user_from_token(authorization) + token = authorization.split(" ")[1] + + conn = get_db_connection() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM sessions WHERE token = %s", (token,)) + conn.commit() + finally: + conn.close() + + return Response( + status_code=204, + headers={"X-Request-Id": req_id, "X-Instance-Id": "instance-1"}, + ) @app.get("/api/v1/users/me") -def current_user(response: Response, x_user_id: Optional[str] = Header(None)): +def current_user(response: Response, authorization: Optional[str] = Header(None)): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id - return get_current_user(x_user_id) + response.headers["X-Instance-Id"] = "instance-1" + return get_current_user_from_token(authorization) @app.post("/api/v1/chats", status_code=201) -def create_chat(body: CreateChat, response: Response, x_user_id: Optional[str] = Header(None)): +def create_chat(body: CreateChat, response: Response, authorization: Optional[str] = Header(None)): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id - user = get_current_user(x_user_id) + response.headers["X-Instance-Id"] = "instance-1" + user = get_current_user_from_token(authorization) member_ids_str = [str(mid) for mid in body.member_ids] @@ -145,56 +364,93 @@ def create_chat(body: CreateChat, response: Response, x_user_id: Optional[str] = raise HTTPException(status_code=400, detail="Caller must be in member_ids") if len(member_ids_str) != len(set(member_ids_str)): raise HTTPException(status_code=400, detail="Duplicate member IDs") - for mid_str in member_ids_str: - if mid_str not in USERS: - raise HTTPException(status_code=400, detail=f"User {mid_str} not found") - + + conn = get_db_connection() + with conn.cursor() as cur: + for mid_str in member_ids_str: + cur.execute("SELECT id FROM users WHERE id = %s", (mid_str,)) + if not cur.fetchone(): + conn.close() + raise HTTPException(status_code=400, detail=f"User {mid_str} not found") + chat_id = str(uuid.uuid4()) - created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - chat_obj = { + created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + conn = get_db_connection() + try: + with conn.cursor() as cur: + cur.execute( + "INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)", + (chat_id, body.title, created_at) + ) + for mid_str in member_ids_str: + cur.execute( + "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", + (chat_id, mid_str) + ) + conn.commit() + except Exception: + conn.rollback() + conn.close() + raise HTTPException(status_code=500, detail="Internal error creating chat") + conn.close() + + return { "id": chat_id, "title": body.title, "member_ids": member_ids_str, "created_at": created_at } - CHATS[chat_id] = chat_obj - MESSAGES[chat_id] = [] - return chat_obj @app.get("/api/v1/chats") -def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response = None, x_user_id: Optional[str] = Header(None)): +def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id - user = get_current_user(x_user_id) + response.headers["X-Instance-Id"] = "instance-1" + user = get_current_user_from_token(authorization) if limit < 1 or limit > 100: raise HTTPException(status_code=400, detail="Invalid limit") - - user_chats = [c for c in CHATS.values() if user["id"] in c["member_ids"]] - user_chats.sort(key=lambda x: (x["created_at"], x["id"])) - + + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + SELECT c.id, c.title, c.created_at FROM chats c + JOIN chat_members cm ON c.id = cm.chat_id + WHERE cm.user_id = %s + ORDER BY c.created_at ASC, c.id ASC + """, (user["id"],)) + rows = cur.fetchall() + conn.close() + + user_chats = [] + for r in rows: + # Get members for each chat + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],)) + m_rows = cur.fetchall() + conn.close() + user_chats.append({ + "id": r['id'], + "title": r['title'], + "member_ids": [m['user_id'] for m in m_rows], + "created_at": r['created_at'].isoformat().replace("+00:00", "Z") if isinstance(r['created_at'], datetime) else r['created_at'] + }) + start_idx = 0 if cursor: try: parts = cursor.split("_") - if len(parts) < 2: - raise ValueError("Malformed cursor") c_time, c_id = parts[0], parts[1] - found = False for idx, c in enumerate(user_chats): - if (c["created_at"], c["id"]) > (c_time, c_id): - start_idx = idx - found = True - break - if (c["created_at"], c["id"]) == (c_time, c_id): - start_idx = idx + 1 + if (c["created_at"], c["id"]) >= (c_time, c_id): + start_idx = idx if (c["created_at"], c["id"]) > (c_time, c_id) else idx + 1 found = True break if not found: - raise HTTPException(status_code=400, detail="Invalid or foreign cursor") - except HTTPException: - raise + start_idx = len(user_chats) except Exception: raise HTTPException(status_code=400, detail="Invalid cursor format") @@ -207,88 +463,131 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response return {"items": page_items, "next_cursor": next_cursor} @app.get("/api/v1/chats/{chat_id}") -def get_chat(chat_id: UUID, response: Response, x_user_id: Optional[str] = Header(None)): +def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = Header(None)): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id - user = get_current_user(x_user_id) - - chat = CHATS.get(str(chat_id)) - if not chat or user["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) -def create_message(chat_id: UUID, body: CreateMessage, response: Response, x_user_id: Optional[str] = Header(None)): - req_id = generate_request_id() - response.headers["X-Request-Id"] = req_id - user = get_current_user(x_user_id) + response.headers["X-Instance-Id"] = "instance-1" + user = get_current_user_from_token(authorization) chat_id_str = str(chat_id) - chat = CHATS.get(chat_id_str) - if not chat or user["id"] not in chat["member_ids"]: + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + SELECT c.* FROM chats c + JOIN chat_members cm ON c.id = cm.chat_id + WHERE c.id = %s AND cm.user_id = %s + """, (chat_id_str, user["id"])) + chat = cur.fetchone() + if chat: + cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id_str,)) + members = cur.fetchall() + conn.close() + + if not chat: raise HTTPException(status_code=404, detail="Chat not found") - + + return { + "id": chat['id'], + "title": chat['title'], + "member_ids": [m['user_id'] for m in members], + "created_at": chat['created_at'].isoformat().replace("+00:00", "Z") if isinstance(chat['created_at'], datetime) else chat['created_at'] + } + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +def create_message(chat_id: UUID, body: CreateMessage, response: Response, authorization: Optional[str] = Header(None)): + req_id = generate_request_id() + response.headers["X-Request-Id"] = req_id + response.headers["X-Instance-Id"] = "instance-1" + user = get_current_user_from_token(authorization) + + chat_id_str = str(chat_id) + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s + """, (chat_id_str, user["id"])) + if not cur.fetchone(): + conn.close() + raise HTTPException(status_code=404, detail="Chat not found") + msg_id = str(uuid.uuid4()) - created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - msg_obj = { + created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + with conn.cursor() as cur: + cur.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)", + (msg_id, chat_id_str, user["id"], body.text, created_at) + ) + conn.commit() + conn.close() + + return { "id": msg_id, "chat_id": chat_id_str, "sender_id": user["id"], "text": body.text, "created_at": created_at } - - if chat_id_str not in MESSAGES: - MESSAGES[chat_id_str] = [] - MESSAGES[chat_id_str].append(msg_obj) - - return msg_obj @app.get("/api/v1/chats/{chat_id}/messages") -def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None, response: Response = None, x_user_id: Optional[str] = Header(None)): +def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)): req_id = generate_request_id() response.headers["X-Request-Id"] = req_id - user = get_current_user(x_user_id) + response.headers["X-Instance-Id"] = "instance-1" + user = get_current_user_from_token(authorization) chat_id_str = str(chat_id) - chat = CHATS.get(chat_id_str) - if not chat or user["id"] not in chat["member_ids"]: - raise HTTPException(status_code=404, detail="Chat not found") + conn = get_db_connection() + with conn.cursor() as cur: + cur.execute(""" + SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s + """, (chat_id_str, user["id"])) + if not cur.fetchone(): + conn.close() + raise HTTPException(status_code=404, detail="Chat not found") if limit < 1 or limit > 100: + conn.close() raise HTTPException(status_code=400, detail="Invalid limit") - msgs = MESSAGES.get(chat_id_str, []) - msgs.sort(key=lambda x: (x["created_at"], x["id"])) - + with conn.cursor() as cur: + cur.execute(""" + SELECT id, chat_id, sender_id, text, created_at FROM messages + WHERE chat_id = %s + ORDER BY created_at ASC, id ASC + """, (chat_id_str,)) + msgs = cur.fetchall() + conn.close() + + formatted_msgs = [] + for m in msgs: + formatted_msgs.append({ + "id": m['id'], + "chat_id": m['chat_id'], + "sender_id": m['sender_id'], + "text": m['text'], + "created_at": m['created_at'].isoformat().replace("+00:00", "Z") if isinstance(m['created_at'], datetime) else m['created_at'] + }) + start_idx = 0 if cursor: try: parts = cursor.split("_") - if len(parts) < 2: - raise ValueError("Malformed cursor") c_time, c_id = parts[0], parts[1] - found = False - for idx, m in enumerate(msgs): - if (m["created_at"], m["id"]) > (c_time, c_id): - start_idx = idx - found = True - break - if (m["created_at"], m["id"]) == (c_time, c_id): - start_idx = idx + 1 + for idx, m in enumerate(formatted_msgs): + if (m["created_at"], m["id"]) >= (c_time, c_id): + start_idx = idx if (m["created_at"], m["id"]) > (c_time, c_id) else idx + 1 found = True break if not found: - raise HTTPException(status_code=400, detail="Invalid or foreign cursor") - except HTTPException: - raise + start_idx = len(formatted_msgs) except Exception: raise HTTPException(status_code=400, detail="Invalid cursor format") - page_items = msgs[start_idx:start_idx + limit] + page_items = formatted_msgs[start_idx:start_idx + limit] next_cursor = None - if start_idx + limit < len(msgs): + if start_idx + limit < len(formatted_msgs): last = page_items[-1] next_cursor = f"{last['created_at']}_{last['id']}" diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..0234af1 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,33 @@ +services: + postgres: + image: postgres:15-alpine + environment: + POSTGRES_DB: messenger + POSTGRES_USER: postgres + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d messenger"] + interval: 3s + timeout: 3s + retries: 5 + + api: + build: . + ports: + - "8080:8080" + environment: + - DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/messenger + - SESSION_TTL_SECONDS=3600 + depends_on: + postgres: + condition: service_healthy + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready')"] + interval: 5s + timeout: 3s + retries: 3 + +volumes: + pgdata: \ No newline at end of file diff --git a/migrations/init.sql b/migrations/init.sql new file mode 100644 index 0000000..92dcb06 --- /dev/null +++ b/migrations/init.sql @@ -0,0 +1,38 @@ +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username VARCHAR(32) UNIQUE NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID REFERENCES users(id) ON DELETE CASCADE, + text VARCHAR(4000) NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id); + +CREATE TABLE IF NOT EXISTS sessions ( + token VARCHAR(128) PRIMARY KEY, + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at); \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 2c1181e..8b0b516 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,6 @@ anyio==4.3.0 sniffio==1.3.1 click==8.1.7 h11==0.14.0 -annotated-types==0.6.0 \ No newline at end of file +annotated-types==0.6.0 +psycopg2-binary==2.9.9 +bcrypt==4.1.2 \ No newline at end of file diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 0000000..ce7fdbe --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1,3 @@ +@echo off +docker compose restart +exit /b %ERRORLEVEL% \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..e6cfbc5 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +docker compose restart \ No newline at end of file