feat: implement persistent messenger with PostgreSQL and Redis

This commit is contained in:
sashadugina06
2026-10-30 14:02:09 +03:00
parent 65003b6119
commit bd34c1050a
40 changed files with 2879 additions and 24 deletions
View File
+91
View File
@@ -0,0 +1,91 @@
import base64
import binascii
import hashlib
import os
import re
import secrets
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
password_hasher = PasswordHasher(
time_cost=3,
memory_cost=65536,
parallelism=4,
)
def hash_password(password: str) -> str:
return password_hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return password_hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return False
def parse_basic(authorization: str | None) -> tuple[str, str] | None:
if not authorization:
return None
scheme, separator, credentials = authorization.partition(" ")
if not separator or scheme.lower() != "basic":
return None
try:
raw = base64.b64decode(credentials, validate=True)
decoded = raw.decode("utf-8")
username, password = decoded.split(":", 1)
except (ValueError, UnicodeError, binascii.Error):
return None
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
return None
if not 12 <= len(password) <= 128:
return None
return username, password
def parse_bearer(authorization: str | None) -> str | None:
if not authorization:
return None
scheme, separator, token = authorization.partition(" ")
if not separator or scheme.lower() != "bearer":
return None
if not re.fullmatch(r"[A-Za-z0-9._~+/-]+={0,2}", token) or len(token) > 512:
return None
return token
def create_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
def session_expiration() -> datetime:
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if ttl < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
return datetime.now(timezone.utc) + timedelta(seconds=ttl)
def format_datetime(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(
timespec="microseconds"
).replace("+00:00", "Z")
+234
View File
@@ -0,0 +1,234 @@
from uuid import UUID, uuid4
from .database import get_connection
def serialize_chat(row):
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(member_id) for member_id in row["member_ids"]],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def serialize_message(row):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def create_chat(creator_id, title, member_ids):
chat_id = uuid4()
members = [UUID(member_id) for member_id in member_ids]
with get_connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
cur.execute(
"""
SELECT id
FROM users
WHERE id = ANY(%s::uuid[])
""",
(members,),
)
existing = {row["id"] for row in cur.fetchall()}
if len(existing) != len(members):
return None
cur.execute(
"""
INSERT INTO chats (id, title, created_by)
VALUES (%s, %s, %s)
RETURNING id, title, created_at
""",
(chat_id, title, UUID(creator_id)),
)
chat = cur.fetchone()
cur.executemany(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (%s, %s)
""",
[(chat_id, member_id) for member_id in members],
)
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": member_ids,
"created_at": chat["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def get_chat(chat_id, user_id):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
c.id,
c.title,
c.created_at,
ARRAY(
SELECT cm2.user_id
FROM chat_members cm2
WHERE cm2.chat_id = c.id
ORDER BY cm2.user_id
) AS member_ids
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE c.id = %s
AND cm.user_id = %s
""",
(UUID(chat_id), UUID(user_id)),
)
row = cur.fetchone()
return serialize_chat(row) if row else None
def list_chats(user_id, limit, last_chat_id=None):
with get_connection() as conn:
with conn.cursor() as cur:
last_key = None
if last_chat_id is not None:
cur.execute(
"""
SELECT c.created_at, c.id
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE c.id = %s
AND cm.user_id = %s
""",
(UUID(last_chat_id), UUID(user_id)),
)
last_key = cur.fetchone()
if last_key is None:
return None
cur.execute(
"""
SELECT
c.id,
c.title,
c.created_at,
ARRAY(
SELECT cm2.user_id
FROM chat_members cm2
WHERE cm2.chat_id = c.id
ORDER BY cm2.user_id
) AS member_ids
FROM chats c
JOIN chat_members cm
ON cm.chat_id = c.id
WHERE cm.user_id = %s
AND (
%s::timestamptz IS NULL
OR (c.created_at, c.id) >
(%s::timestamptz, %s::uuid)
)
ORDER BY c.created_at, c.id
LIMIT %s
""",
(
UUID(user_id),
last_key["created_at"] if last_key else None,
last_key["created_at"] if last_key else None,
last_key["id"] if last_key else None,
limit + 1,
),
)
rows = cur.fetchall()
return [serialize_chat(row) for row in rows]
def create_message(chat_id, sender_id, text):
message_id = uuid4()
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
SELECT %s, %s, %s, %s
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = %s
AND user_id = %s
)
RETURNING id, chat_id, sender_id, text, created_at
""",
(
message_id,
UUID(chat_id),
UUID(sender_id),
text,
UUID(chat_id),
UUID(sender_id),
),
)
row = cur.fetchone()
return serialize_message(row) if row else None
def list_messages(chat_id, limit, last_message_id=None):
with get_connection() as conn:
with conn.cursor() as cur:
last_key = None
if last_message_id is not None:
cur.execute(
"""
SELECT created_at, id
FROM messages
WHERE chat_id = %s
AND id = %s
""",
(UUID(chat_id), UUID(last_message_id)),
)
last_key = cur.fetchone()
if last_key is None:
return None
# Разные формы SQL сохраняют индексный range scan и для generic plan.
# В SQL подставляется только константа; значения остаются параметрами.
cursor_condition = ""
params = [UUID(chat_id)]
if last_key is not None:
cursor_condition = "AND (created_at, id) > (%s, %s)"
params.extend([last_key["created_at"], last_key["id"]])
params.append(limit + 1)
cur.execute(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s
{cursor_condition}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
rows = cur.fetchall()
return [serialize_message(row) for row in rows]
+48
View File
@@ -0,0 +1,48 @@
import os
from contextlib import contextmanager
from pathlib import Path
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
def get_database_url() -> str:
secret_file = os.getenv("DATABASE_URL_FILE")
if secret_file:
return Path(secret_file).read_text().strip()
database_url = os.getenv("DATABASE_URL")
if database_url:
return database_url
raise RuntimeError("Database connection is not configured")
pool = ConnectionPool(
conninfo=get_database_url(),
min_size=1,
max_size=10,
timeout=5,
open=False,
kwargs={
"row_factory": dict_row,
"connect_timeout": 5,
"options": "-c statement_timeout=5000",
},
)
def open_database():
pool.open(wait=True, timeout=15)
def close_database():
pool.close()
@contextmanager
def get_connection():
with pool.connection() as connection:
yield connection
+478
View File
@@ -0,0 +1,478 @@
"""Мессенджер: PostgreSQL хранит данные и сессии, Redis кеширует профили."""
import base64
import binascii
import logging
import re
from uuid import UUID, uuid4
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from psycopg import OperationalError
from psycopg_pool import PoolTimeout
from .auth import (
create_token,
format_datetime,
hash_password,
hash_token,
parse_basic,
parse_bearer,
session_expiration,
verify_password,
)
from .database import open_database, close_database, get_connection
from .user_repository import (
create_user as insert_user,
create_session,
find_session_user_cached,
find_user_by_username,
revoke_session,
serialize_user,
)
from .chat_repository import (
create_chat as insert_chat,
get_chat as find_chat,
list_chats as find_chats,
create_message as insert_message,
list_messages as find_messages,
)
app = FastAPI(title="MTUSI Messenger", version="1.2.0")
logger = logging.getLogger("uvicorn.error")
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
500: "internal_error",
503: "unavailable",
}
def error_response(request, status_code, code, message):
return JSONResponse(
status_code=status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request.state.request_id,
}
},
)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
response = await call_next(request)
except Exception:
# Логируем путь, метод и request_id, но НЕ тело сообщения.
logger.error(
"Unhandled error: %s %s request_id=%s",
request.method,
request.url.path,
request.state.request_id,
)
response = error_response(
request, 500, "internal_error", "Внутренняя ошибка сервера"
)
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException):
response = error_response(
request,
exc.status_code,
ERROR_CODES.get(exc.status_code, "invalid_request"),
str(exc.detail),
)
if exc.headers:
response.headers.update(exc.headers)
return response
@app.exception_handler(OperationalError)
@app.exception_handler(PoolTimeout)
async def database_error_handler(request: Request, exc):
return error_response(request, 503, "unavailable", "База данных временно недоступна")
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "Некорректные данные запроса")
async def read_json(request: Request):
"""415 — только для неправильного Content-Type; 400 — для неверного JSON."""
content_type = (
request.headers.get("content-type", "").split(";")[0].strip().lower()
)
if content_type != "application/json":
raise HTTPException(415, "Неподдерживаемый Content-Type")
try:
data = await request.json()
except (ValueError, UnicodeError):
raise HTTPException(400, "Неверный JSON") from None
# [], строка, число, true, false, null — это корректный JSON,
# но НЕ объект, обязательный по контракту.
if not isinstance(data, dict):
raise HTTPException(400, "Ожидается JSON-объект")
return data
def get_current_user(request: Request):
token = parse_bearer(request.headers.get("Authorization"))
if token is None:
raise HTTPException(
401,
"Требуется действующий Bearer-токен",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
try:
user = find_session_user_cached(hash_token(token))
except (OperationalError, PoolTimeout):
raise HTTPException(
503,
"База данных временно недоступна",
) from None
if user is None:
raise HTTPException(
401,
"Недействительная или истёкшая сессия",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return user
def get_limit(request: Request):
"""Проверяем длину ДО int(): 5000 цифр должны дать 400, а не 500."""
limit_raw = request.query_params.get("limit", "50")
if not limit_raw.isascii() or not limit_raw.isdecimal():
raise HTTPException(400, "Неверный limit")
significant = limit_raw.lstrip("0")
if not significant or len(significant) > 3:
raise HTTPException(400, "Неверный limit")
limit = int(significant) # Теперь строка содержит максимум 3 цифры.
if not 1 <= limit <= 100:
raise HTTPException(400, "limit должен быть от 1 до 100")
return limit
def encode_cursor(first_id, last_id):
raw = f"{first_id}|{last_id}".encode("ascii")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor):
try:
if not cursor or len(cursor) > 256:
raise ValueError("empty or too long")
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.b64decode(
padded, altchars=b"-_", validate=True
).decode("ascii")
first_id, last_id = raw.split("|")
return str(UUID(first_id)), str(UUID(last_id))
except (ValueError, UnicodeError, binascii.Error):
raise HTTPException(400, "Неверный cursor") from None
# ---- Health ----
@app.get("/health/live")
def health_live():
return {"status": "ok"}
@app.get("/health/ready")
def health_ready():
try:
with get_connection() as conn:
conn.execute("SELECT 1")
except (OperationalError, PoolTimeout):
raise HTTPException(503, "База данных недоступна") from None
return {"status": "ok"}
# ---- Users ----
@app.post("/api/v1/users", status_code=201)
async def create_user(request: Request):
data = await read_json(request)
if set(data) != {"username", "display_name", "password"}:
raise HTTPException(400, "Неверные поля пользователя")
username = data["username"]
display_name = data["display_name"]
password = data["password"]
if not isinstance(username, str) or not re.fullmatch(
r"[a-z0-9_]{3,32}", username
):
raise HTTPException(400, "Недопустимый username")
if (
not isinstance(display_name, str)
or not 1 <= len(display_name) <= 100
or not display_name.strip()
):
raise HTTPException(400, "Недопустимое имя пользователя")
if not isinstance(password, str) or not 12 <= len(password) <= 128:
raise HTTPException(400, "Пароль должен содержать 12–128 символов")
user = insert_user(username, display_name, hash_password(password))
if user is None:
raise HTTPException(409, "Username уже занят")
return user
@app.get("/api/v1/users/me")
def get_me(request: Request):
return get_current_user(request)
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(request: Request):
credentials = parse_basic(request.headers.get("Authorization"))
if credentials is None:
raise HTTPException(
401,
"Неверные учётные данные",
headers={
"WWW-Authenticate":
'Basic realm="messenger", charset="UTF-8"'
},
)
username, password = credentials
user_row = find_user_by_username(username)
if user_row is None or not verify_password(
user_row["password_hash"], password
):
raise HTTPException(
401,
"Неверные учётные данные",
headers={
"WWW-Authenticate":
'Basic realm="messenger", charset="UTF-8"'
},
)
token = create_token()
expires_at = session_expiration()
create_session(user_row["id"], hash_token(token), expires_at)
return {
"token": token,
"token_type": "Bearer",
"expires_at": format_datetime(expires_at),
"user": serialize_user(user_row),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request):
get_current_user(request)
token = parse_bearer(request.headers.get("Authorization"))
from .session_cache import invalidate_session
if not revoke_session(hash_token(token)):
raise HTTPException(
401,
"Недействительная сессия",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
invalidate_session(hash_token(token))
from fastapi import Response
return Response(status_code=204)
# ---- Chats ----
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = get_current_user(request)
data = await read_json(request)
if set(data) != {"title", "member_ids"}:
raise HTTPException(400, "Неверные поля чата")
title = data["title"]
member_ids = data["member_ids"]
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
raise HTTPException(400, "Недопустимое название чата")
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
raise HTTPException(400, "Неверный список участников")
normalized_ids = []
for member_id in member_ids:
if not isinstance(member_id, str):
raise HTTPException(400, "Неверный ID участника")
try:
normalized_ids.append(str(UUID(member_id)))
except ValueError:
raise HTTPException(400, "Неверный UUID участника") from None
if len(normalized_ids) != len(set(normalized_ids)):
raise HTTPException(400, "Участники повторяются")
if user["id"] not in normalized_ids:
raise HTTPException(400, "Создатель должен быть участником")
chat = insert_chat(user["id"], title, normalized_ids)
if chat is None:
raise HTTPException(400, "Неизвестный участник")
return chat
@app.get("/api/v1/chats")
def list_chats(request: Request):
user = get_current_user(request)
limit = get_limit(request)
cursor = request.query_params.get("cursor")
last_chat_id = None
if cursor is not None:
cursor_user_id, last_chat_id = decode_cursor(cursor)
if cursor_user_id != user["id"]:
raise HTTPException(400, "Неверный cursor")
rows = find_chats(user["id"], limit, last_chat_id)
if rows is None:
raise HTTPException(400, "Неверный cursor")
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = (
encode_cursor(user["id"], page[-1]["id"])
if has_more and page
else None
)
return {"items": page, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
user = get_current_user(request)
try:
chat_id = str(UUID(chat_id))
except ValueError:
raise HTTPException(400, "Неверный UUID чата") from None
chat = find_chat(chat_id, user["id"])
if chat is None:
raise HTTPException(404, "Чат не найден")
return chat
# ---- Messages ----
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def send_message(chat_id: str, request: Request):
user = get_current_user(request)
chat = get_chat(chat_id, request)
data = await read_json(request)
if set(data) != {"text"}:
raise HTTPException(400, "Неверные поля сообщения")
text = data["text"]
if not isinstance(text, str) or not 1 <= len(text) <= 4000 or not text.strip():
raise HTTPException(400, "Недопустимый текст сообщения")
message = insert_message(chat["id"], user["id"], text)
if message is None:
raise HTTPException(404, "Чат не найден")
return message
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request):
chat = get_chat(chat_id, request)
limit = get_limit(request)
cursor = request.query_params.get("cursor")
last_message_id = None
if cursor is not None:
cursor_chat_id, last_message_id = decode_cursor(cursor)
if cursor_chat_id != chat["id"]:
raise HTTPException(400, "Неверный cursor")
rows = find_messages(chat["id"], limit, last_message_id)
if rows is None:
raise HTTPException(400, "Неверный cursor")
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = (
encode_cursor(chat["id"], page[-1]["id"])
if has_more and page
else None
)
return {"items": page, "next_cursor": next_cursor}
@app.on_event("startup")
def start_database_pool():
open_database()
@app.on_event("shutdown")
def stop_database_pool():
close_database()
+48
View File
@@ -0,0 +1,48 @@
import json
import os
from pathlib import Path
import redis
def get_cache_url():
secret_file = os.getenv("CACHE_URL_FILE")
if secret_file:
return Path(secret_file).read_text().strip()
return os.getenv("CACHE_URL", "redis://redis:6379/0")
client = redis.Redis.from_url(
get_cache_url(),
socket_connect_timeout=1,
socket_timeout=1,
decode_responses=True,
)
def get_cached_user(token_hash):
try:
value = client.get("session:" + token_hash)
return json.loads(value) if value else None
except (redis.RedisError, ValueError):
return None
def cache_user(token_hash, user, ttl):
if ttl <= 0:
return
try:
client.setex(
"session:" + token_hash,
ttl,
json.dumps(user),
)
except redis.RedisError:
pass
def invalidate_session(token_hash):
try:
client.delete("session:" + token_hash)
except redis.RedisError:
pass
+136
View File
@@ -0,0 +1,136 @@
from uuid import uuid4
from psycopg.errors import UniqueViolation
from .database import get_connection
def serialize_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": row["created_at"].isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
}
def create_user(username, display_name, password_hash):
with get_connection() as conn:
with conn.cursor() as cur:
try:
cur.execute(
"""
INSERT INTO users (
id, username, display_name, password_hash
)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(uuid4(), username, display_name, password_hash),
)
return serialize_user(cur.fetchone())
except UniqueViolation:
conn.rollback()
return None
def find_user_by_username(username):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, username, display_name,
password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
)
return cur.fetchone()
def create_session(user_id, token_hash, expires_at):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO sessions (
id, user_id, token_hash, expires_at
)
VALUES (%s, %s, %s, %s)
""",
(uuid4(), user_id, token_hash, expires_at),
)
def revoke_session(token_hash):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE sessions
SET revoked_at = NOW()
WHERE token_hash = %s
AND revoked_at IS NULL
AND expires_at > NOW()
RETURNING id
""",
(token_hash,),
)
return cur.fetchone() is not None
def find_session_user_cached(token_hash):
from datetime import datetime, timezone
from .session_cache import cache_user, get_cached_user
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
s.user_id,
s.expires_at
FROM sessions s
WHERE s.token_hash = %s
AND s.revoked_at IS NULL
AND s.expires_at > NOW()
""",
(token_hash,),
)
session = cur.fetchone()
if session is None:
return None
cached = get_cached_user(token_hash)
if cached is not None and str(cached.get("id")) == str(session["user_id"]):
return cached
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(session["user_id"],),
)
row = cur.fetchone()
if row is None:
return None
user = serialize_user(row)
ttl = int(
(session["expires_at"] - datetime.now(timezone.utc)).total_seconds()
)
if ttl > 0:
cache_user(token_hash, user, ttl)
return user