Implement lab3 replicated API and experiment evidence

This commit is contained in:
Polusikkkk
2026-10-29 20:20:13 +03:00
parent 0ab3a341aa
commit 5847952e76
48 changed files with 4013 additions and 33 deletions
View File
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import base64
import binascii
import hashlib
import re
import secrets
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerificationError
from starlette.concurrency import run_in_threadpool
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}", re.ASCII)
password_hasher = PasswordHasher(
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
salt_len=16,
type=Type.ID,
)
DUMMY_PASSWORD_HASH = password_hasher.hash(
secrets.token_urlsafe(32)
)
async def hash_password(password: str) -> str:
return await run_in_threadpool(
password_hasher.hash,
password,
)
async def verify_password(
password_hash: str,
password: str,
) -> bool:
try:
return await run_in_threadpool(
password_hasher.verify,
password_hash,
password,
)
except VerificationError:
return False
def parse_basic_credentials(
authorization: str | None,
) -> tuple[str, str] | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "basic":
return None
try:
decoded = base64.b64decode(
parts[1],
validate=True,
).decode("utf-8")
except (binascii.Error, UnicodeError, ValueError):
return None
username, separator, password = decoded.partition(":")
if not separator:
return None
if USERNAME_RE.fullmatch(username) is None:
return None
if not 12 <= len(password) <= 128:
return None
return username, password
def parse_bearer_token(
authorization: str | None,
) -> str | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return None
token = parts[1]
if re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
return None
return token
def generate_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
+129
View File
@@ -0,0 +1,129 @@
from __future__ import annotations
import json
import logging
import os
from datetime import datetime, timezone
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from app.store import store
logger = logging.getLogger("messenger.cache")
CACHE_TTL_SECONDS = int(
os.getenv("USER_CACHE_TTL_SECONDS", "60")
)
if not 1 <= CACHE_TTL_SECONDS <= 3600:
raise ValueError(
"USER_CACHE_TTL_SECONDS must be between 1 and 3600"
)
redis_client = Redis(
host=os.getenv("REDIS_HOST", "redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
decode_responses=True,
socket_connect_timeout=0.2,
socket_timeout=0.2,
retry_on_timeout=False,
max_connections=10,
)
def serialize_user(user: dict) -> str:
created_at = user["created_at"]
return json.dumps(
{
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": created_at.astimezone(
timezone.utc
).isoformat().replace("+00:00", "Z"),
},
ensure_ascii=False,
separators=(",", ":"),
)
def deserialize_user(
raw: str,
expected_id: UUID,
) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("Invalid cached user")
expected_fields = {
"id",
"username",
"display_name",
"created_at",
}
if set(data) != expected_fields:
raise ValueError("Invalid cached user fields")
if not all(isinstance(value, str) for value in data.values()):
raise ValueError("Invalid cached user types")
user_id = UUID(data["id"])
if user_id != expected_id:
raise ValueError("Cached user ID mismatch")
created_at = datetime.fromisoformat(
data["created_at"].replace("Z", "+00:00")
)
if created_at.tzinfo is None:
raise ValueError("Cached timestamp has no timezone")
return {
"id": user_id,
"username": data["username"],
"display_name": data["display_name"],
"created_at": created_at,
}
async def get_cached_user(user_id: UUID) -> dict | None:
key = f"user:v1:{user_id}"
try:
raw = await redis_client.get(key)
if raw is not None:
return deserialize_user(raw, user_id)
except RedisError:
logger.warning("User cache read unavailable")
except (ValueError, TypeError, OverflowError):
logger.warning("Invalid user cache entry ignored")
user = await store.get_user(user_id)
if user is None:
return None
try:
await redis_client.set(
key,
serialize_user(user),
ex=CACHE_TTL_SECONDS,
)
except RedisError:
logger.warning("User cache write unavailable")
return user
async def close_cache() -> None:
await redis_client.aclose()
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
import os
SESSION_TTL_SECONDS = int(
os.getenv("SESSION_TTL_SECONDS", "3600")
)
if SESSION_TTL_SECONDS < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
+44
View File
@@ -0,0 +1,44 @@
from __future__ import annotations
import os
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
pool = AsyncConnectionPool(
conninfo="",
kwargs={
"host": os.getenv("PGHOST", "postgres"),
"port": int(os.getenv("PGPORT", "5432")),
"dbname": os.getenv("PGDATABASE", "messenger"),
"user": os.getenv("PGUSER", "messenger"),
"password": os.environ.get("PGPASSWORD", ""),
"connect_timeout": 3,
"options": (
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
"row_factory": dict_row,
},
min_size=1,
max_size=5,
timeout=3,
max_waiting=20,
open=False,
check=AsyncConnectionPool.check_connection,
)
async def open_db() -> None:
await pool.open(wait=True, timeout=10)
async def close_db() -> None:
await pool.close()
async def check_db() -> None:
async with pool.connection() as conn:
await conn.execute("SELECT 1")
+48
View File
@@ -0,0 +1,48 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.auth import hash_token, parse_bearer_token
from app.cache import get_cached_user
from app.errors import not_found, unauthorized
from app.store import store
from app.validation import parse_uuid
async def current_user(request: Request) -> tuple[dict, str]:
token = parse_bearer_token(
request.headers.get("authorization")
)
if token is None:
raise unauthorized()
token_digest = hash_token(token)
user_id = await store.get_session_user_id(token_digest)
if user_id is None:
raise unauthorized()
user = await get_cached_user(user_id)
if user is None:
raise unauthorized()
return user, token_digest
async def accessible_chat(
raw_chat_id: str,
user_id: UUID,
) -> tuple[UUID, dict]:
chat_id = parse_uuid(raw_chat_id)
chat = await store.get_accessible_chat(chat_id, user_id)
if chat is None:
raise not_found()
return chat_id, chat
+71
View File
@@ -0,0 +1,71 @@
from __future__ import annotations
from uuid import uuid4
from fastapi import Request
from fastapi.responses import JSONResponse
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
challenge: str | None = None,
):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.challenge = challenge
def invalid(message: str = "Некорректный запрос") -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(scheme: str = "Bearer") -> ApiError:
if scheme == "Basic":
challenge = 'Basic realm="messenger", charset="UTF-8"'
else:
challenge = 'Bearer realm="messenger"'
return ApiError(
401,
"unauthorized",
"Недействительная аутентификация",
challenge,
)
def not_found() -> ApiError:
return ApiError(404, "not_found", "Объект не найден")
def error_response(
request: Request,
error: ApiError,
) -> JSONResponse:
request_id = getattr(
request.state,
"request_id",
str(uuid4()),
)
headers = {"X-Request-Id": request_id}
if error.challenge is not None:
headers["WWW-Authenticate"] = error.challenge
return JSONResponse(
status_code=error.status,
content={
"error": {
"code": error.code,
"message": error.message,
"request_id": request_id,
}
},
headers=headers,
)
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import hashlib
import json
from uuid import UUID, uuid4
from app.db import pool
from app.errors import ApiError
async def create_message_once(
chat_id: UUID,
sender_id: UUID,
text: str,
key: str,
) -> dict:
scope = json.dumps(
[
str(sender_id),
"POST",
f"/api/v1/chats/{chat_id}/messages",
key,
],
separators=(",", ":"),
)
lock_id = int.from_bytes(
hashlib.sha256(scope.encode("utf-8")).digest()[:8],
byteorder="big",
signed=True,
)
async with pool.connection() as conn:
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(lock_id,),
)
cursor = await conn.execute(
"""
SELECT i.request_text,
m.id, m.chat_id, m.sender_id,
m.text, m.created_at
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = %s
AND i.chat_id = %s
AND i.http_method = 'POST'
AND i.idempotency_key = %s
""",
(sender_id, chat_id, key),
)
previous = await cursor.fetchone()
if previous is not None:
if previous["request_text"] != text:
raise ApiError(
409,
"conflict",
"Ключ уже использован с другим сообщением",
)
message = {
field: previous[field]
for field in (
"id",
"chat_id",
"sender_id",
"text",
"created_at",
)
}
else:
cursor = await conn.execute(
"""
INSERT INTO messages (
id, chat_id, sender_id, text
)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id,
text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
await conn.execute(
"""
INSERT INTO message_idempotency (
user_id,
chat_id,
http_method,
idempotency_key,
request_text,
message_id
)
VALUES (%s, %s, 'POST', %s, %s, %s)
""",
(
sender_id,
chat_id,
key,
text,
message["id"],
),
)
return message
+7
View File
@@ -0,0 +1,7 @@
from __future__ import annotations
import socket
from uuid import uuid4
INSTANCE_ID = f"{socket.gethostname()}:{uuid4().hex[:12]}"
+114
View File
@@ -0,0 +1,114 @@
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from psycopg import InterfaceError, OperationalError
from psycopg.errors import LockNotAvailable, QueryCanceled
from psycopg_pool import PoolTimeout, TooManyRequests
from starlette.exceptions import HTTPException
from app.cache import close_cache
from app.instance import INSTANCE_ID
from app.db import close_db, open_db
from app.errors import ApiError, error_response, invalid, not_found
from app.routers import chats, health, messages, sessions, users
logger = logging.getLogger("messenger.api")
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
await open_db()
yield
finally:
await close_cache()
await close_db()
app = FastAPI(
title="Replicated PostgreSQL messenger — Lab 3",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
response = await call_next(request)
except ApiError as exc:
response = error_response(request, exc)
except (
OperationalError,
InterfaceError,
PoolTimeout,
TooManyRequests,
QueryCanceled,
LockNotAvailable,
) as exc:
logger.warning(
"Database unavailable request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
503,
"unavailable",
"Сервис временно недоступен",
),
)
except Exception as exc:
logger.error(
"Unhandled error request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
500,
"internal_error",
"Внутренняя ошибка сервера",
),
)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc):
return error_response(request, invalid())
@app.exception_handler(HTTPException)
async def http_error_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
error = not_found()
else:
error = invalid("Недопустимый HTTP-запрос")
return error_response(request, error)
app.include_router(health.router)
app.include_router(users.router)
app.include_router(sessions.router)
app.include_router(chats.router)
app.include_router(messages.router)
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import hashlib
import os
from pathlib import Path
import psycopg
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
MIGRATION_LOCK_ID = 202602001
def apply_migrations() -> None:
files = sorted(MIGRATIONS_DIR.glob("[0-9]*_*.sql"))
if not files:
raise RuntimeError("Migration files not found")
with psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=5,
options="-c statement_timeout=30000 -c lock_timeout=10000",
) as conn:
conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(MIGRATION_LOCK_ID,),
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL
DEFAULT clock_timestamp()
)
"""
)
for path in files:
version = path.name
content = path.read_bytes()
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute(
"""
SELECT checksum
FROM schema_migrations
WHERE version = %s
""",
(version,),
).fetchone()
if row is not None:
if row[0] != checksum:
raise RuntimeError(
f"Applied migration was modified: {version}"
)
print(f"Already applied: {version}", flush=True)
continue
conn.execute(content.decode("utf-8"), prepare=False)
conn.execute(
"""
INSERT INTO schema_migrations (version, checksum)
VALUES (%s, %s)
""",
(version, checksum),
)
print(f"Executed: {version} (pending commit)", flush=True)
print("Migrations committed successfully", flush=True)
if __name__ == "__main__":
apply_migrations()
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
import base64
import binascii
import json
import re
from datetime import datetime
from uuid import UUID
from fastapi import Request
from fastapi.responses import JSONResponse
from app.errors import invalid
from app.responses import json_response, utc_text
def encode_cursor(scope: str, item: dict) -> str:
raw = json.dumps(
{
"scope": scope,
"created_at": utc_text(item["created_at"]),
"id": str(item["id"]),
},
separators=(",", ":"),
).encode("utf-8")
return (
base64.urlsafe_b64encode(raw)
.decode("ascii")
.rstrip("=")
)
def decode_cursor(
cursor: str,
scope: str,
) -> tuple[datetime, UUID]:
if not cursor or len(cursor) > 2048:
raise invalid("Некорректный cursor")
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.b64decode(
padded,
altchars=b"-_",
validate=True,
)
data = json.loads(raw.decode("utf-8"))
if (
not isinstance(data, dict)
or set(data) != {"scope", "created_at", "id"}
or data["scope"] != scope
):
raise ValueError
timestamp = data["created_at"]
if (
not isinstance(timestamp, str)
or not timestamp.endswith("Z")
or not isinstance(data["id"], str)
):
raise ValueError
created_at = datetime.fromisoformat(
timestamp[:-1] + "+00:00"
)
item_id = UUID(data["id"])
return created_at, item_id
except (
ValueError,
TypeError,
UnicodeError,
binascii.Error,
OverflowError,
):
raise invalid("Некорректный cursor") from None
def pagination(
request: Request,
scope: str,
) -> tuple[int, tuple[datetime, UUID] | None]:
raw_limit = request.query_params.get("limit", "50")
if (
len(raw_limit) > 10
or re.fullmatch(r"[0-9]+", raw_limit) is None
):
raise invalid("Некорректный limit")
limit = int(raw_limit)
if not 1 <= limit <= 100:
raise invalid("Некорректный limit")
raw_cursor = request.query_params.get("cursor")
after = None
if raw_cursor is not None:
after = decode_cursor(raw_cursor, scope)
return limit, after
def page_response(
rows: list[dict],
limit: int,
scope: str,
) -> JSONResponse:
items = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor(scope, items[-1])
return json_response(
{
"items": items,
"next_cursor": next_cursor,
}
)
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID
from fastapi.responses import JSONResponse
def utc_text(value: datetime) -> str:
return (
value.astimezone(timezone.utc)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
def to_json(value):
if isinstance(value, UUID):
return str(value)
if isinstance(value, datetime):
return utc_text(value)
if isinstance(value, dict):
return {
key: to_json(item)
for key, item in value.items()
}
if isinstance(value, (list, tuple)):
return [to_json(item) for item in value]
return value
def json_response(value, status: int = 200) -> JSONResponse:
return JSONResponse(
status_code=status,
content=to_json(value),
)
View File
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import InvalidMembersError, store
from app.validation import parse_uuid, read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/chats")
async def create_chat(request: Request):
user, _ = await current_user(request)
payload = await read_payload(
request,
{"title", "member_ids"},
)
if not valid_text(payload["title"], 100):
raise invalid("Некорректный title")
raw_members = payload["member_ids"]
if (
not isinstance(raw_members, list)
or not 1 <= len(raw_members) <= 100
):
raise invalid("Некорректный member_ids")
member_ids = [parse_uuid(item) for item in raw_members]
if len(set(member_ids)) != len(member_ids):
raise invalid("В member_ids есть дубликаты")
if user["id"] not in member_ids:
raise invalid("Создатель должен входить в member_ids")
try:
chat = await store.create_chat(
payload["title"],
member_ids,
)
except InvalidMembersError:
raise invalid(
"В member_ids есть неизвестный пользователь"
) from None
return json_response(chat, 201)
@router.get("/api/v1/chats")
async def list_chats(request: Request):
user, _ = await current_user(request)
scope = f"chats:{user['id']}"
limit, after = pagination(request, scope)
rows = await store.list_chats(user["id"], limit, after)
return page_response(rows, limit, scope)
@router.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
user, _ = await current_user(request)
_, chat = await accessible_chat(chat_id, user["id"])
return json_response(chat)
+18
View File
@@ -0,0 +1,18 @@
from __future__ import annotations
from fastapi import APIRouter
from app.db import check_db
router = APIRouter()
@router.get("/health/live")
async def health_live():
return {"status": "ok"}
@router.get("/health/ready")
async def health_ready():
await check_db()
return {"status": "ok"}
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import re
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.idempotency import create_message_once
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import store
from app.validation import read_payload, valid_text
router = APIRouter()
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
@router.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
keys = request.headers.getlist("idempotency-key")
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
raise invalid("Требуется корректный Idempotency-Key")
payload = await read_payload(
request,
{"text"},
optional_fields={"attachment_ids"},
)
if not valid_text(payload["text"], 4000):
raise invalid("Некорректный текст сообщения")
attachments = payload.get("attachment_ids", [])
if not isinstance(attachments, list) or attachments:
raise invalid("В ЛР 3 поддерживаются сообщения без вложений")
message = await create_message_once(
chat_uuid,
user["id"],
payload["text"],
keys[0],
)
return json_response(message, 201)
@router.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
scope = f"messages:{chat_uuid}"
limit, after = pagination(request, scope)
rows = await store.list_messages(
chat_uuid,
limit,
after,
)
return page_response(rows, limit, scope)
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from fastapi.responses import Response
from app.auth import (
DUMMY_PASSWORD_HASH,
generate_token,
hash_token,
parse_basic_credentials,
verify_password,
)
from app.config import SESSION_TTL_SECONDS
from app.dependencies import current_user
from app.errors import invalid, unauthorized
from app.responses import json_response
from app.store import store
router = APIRouter()
@router.post("/api/v1/auth/sessions")
async def create_session(request: Request):
credentials = parse_basic_credentials(
request.headers.get("authorization")
)
if credentials is None:
raise unauthorized("Basic")
username, password = credentials
user = await store.get_user_for_login(username)
stored_hash = (
DUMMY_PASSWORD_HASH
if user is None
else user["password_hash"]
)
password_ok = await verify_password(stored_hash, password)
if user is None or not password_ok:
raise unauthorized("Basic")
if await request.body():
raise invalid("Тело запроса при входе не допускается")
token = generate_token()
session = await store.create_session(
user["id"],
hash_token(token),
SESSION_TTL_SECONDS,
)
public_user = {
field: user[field]
for field in ("id", "username", "display_name", "created_at")
}
return json_response(
{
"token": token,
"token_type": "Bearer",
"expires_at": session["expires_at"],
"user": public_user,
},
201,
)
@router.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
_, token_digest = await current_user(request)
revoked = await store.revoke_session(token_digest)
if not revoked:
raise unauthorized()
return Response(status_code=204)
+59
View File
@@ -0,0 +1,59 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.auth import USERNAME_RE, hash_password
from app.dependencies import current_user
from app.errors import ApiError, invalid
from app.responses import json_response
from app.store import store
from app.validation import read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/users")
async def create_user(request: Request):
payload = await read_payload(
request,
{"username", "display_name", "password"},
)
username = payload["username"]
display_name = payload["display_name"]
password = payload["password"]
if (
not isinstance(username, str)
or USERNAME_RE.fullmatch(username) is None
):
raise invalid("Некорректный username")
if not valid_text(display_name, 100):
raise invalid("Некорректное display_name")
if not valid_text(password, 128) or len(password) < 12:
raise invalid("Пароль должен содержать от 12 до 128 символов")
password_digest = await hash_password(password)
user = await store.create_user(
username,
display_name,
password_digest,
)
if user is None:
raise ApiError(
409,
"conflict",
"Username уже занят",
)
return json_response(user, 201)
@router.get("/api/v1/users/me")
async def get_current_user(request: Request):
user, _ = await current_user(request)
return json_response(user)
+273
View File
@@ -0,0 +1,273 @@
from __future__ import annotations
from datetime import datetime
from uuid import UUID, uuid4
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from app.db import pool
class InvalidMembersError(Exception):
pass
class PostgresStore:
async def create_user(
self,
username: str,
display_name: str,
password_hash: str,
) -> dict | None:
try:
async with pool.connection() as conn:
cursor = await conn.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),
)
user = await cursor.fetchone()
return user
except UniqueViolation as exc:
if exc.diag.constraint_name == "users_username_unique":
return None
raise
async def get_user(self, user_id: UUID) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
)
return await cursor.fetchone()
async def get_user_for_login(self, username: str) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name,
password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
)
return await cursor.fetchone()
async def create_chat(
self,
title: str,
member_ids: list[UUID],
) -> dict:
chat_id = uuid4()
try:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO chats (id, title)
VALUES (%s, %s)
RETURNING id, title, created_at
""",
(chat_id, title),
)
chat = await cursor.fetchone()
async with conn.cursor() as cursor:
await cursor.executemany(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (%s, %s)
""",
[(chat_id, user_id) for user_id in member_ids],
)
chat["member_ids"] = member_ids
return chat
except ForeignKeyViolation as exc:
raise InvalidMembersError from exc
async def get_accessible_chat(
self,
chat_id: UUID,
user_id: UUID,
) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
WHERE c.id = %s
AND EXISTS (
SELECT 1
FROM chat_members AS access
WHERE access.chat_id = c.id
AND access.user_id = %s
)
""",
(chat_id, user_id),
)
return await cursor.fetchone()
async def list_chats(
self,
user_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [user_id]
after_sql = ""
if after is not None:
after_sql = "AND (c.created_at, c.id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
JOIN chat_members AS access
ON access.chat_id = c.id
WHERE access.user_id = %s
{after_sql}
ORDER BY c.created_at, c.id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_message(
self,
chat_id: UUID,
sender_id: UUID,
text: str,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
return message
async def list_messages(
self,
chat_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [chat_id]
after_sql = ""
if after is not None:
after_sql = "AND (created_at, id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s
{after_sql}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_session(
self,
user_id: UUID,
token_hash: str,
ttl_seconds: int,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO sessions (
token_hash, user_id, created_at, expires_at
)
VALUES (
%s, %s, statement_timestamp(),
statement_timestamp()
+ (%s * INTERVAL '1 second')
)
RETURNING expires_at
""",
(token_hash, user_id, ttl_seconds),
)
session = await cursor.fetchone()
return session
async def get_session_user_id(
self,
token_hash: str,
) -> UUID | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT user_id
FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
""",
(token_hash,),
)
row = await cursor.fetchone()
return None if row is None else row["user_id"]
async def revoke_session(self, token_hash: str) -> bool:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
DELETE FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
RETURNING token_hash
""",
(token_hash,),
)
row = await cursor.fetchone()
return row is not None
store = PostgresStore()
+61
View File
@@ -0,0 +1,61 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.errors import ApiError, invalid
def parse_uuid(value: object) -> UUID:
if not isinstance(value, str):
raise invalid("Некорректный UUID")
try:
return UUID(value)
except ValueError:
raise invalid("Некорректный UUID") from None
def valid_text(value: object, maximum: int) -> bool:
return (
isinstance(value, str)
and 1 <= len(value) <= maximum
and bool(value.strip())
)
async def read_payload(
request: Request,
expected_fields: set[str],
optional_fields: set[str] | None = None,
) -> dict:
content_type = (
request.headers.get("content-type", "")
.split(";", 1)[0]
.strip()
.lower()
)
if content_type != "application/json":
raise ApiError(
415,
"unsupported_media_type",
"Требуется Content-Type: application/json",
)
try:
payload = await request.json()
except (ValueError, UnicodeError):
raise invalid("Некорректный JSON") from None
allowed_fields = expected_fields | (optional_fields or set())
if (
not isinstance(payload, dict)
or not expected_fields.issubset(payload)
or not set(payload).issubset(allowed_fields)
):
raise invalid("Некорректные поля запроса")
return payload