ЛР 3 — БПИ2302 — Щербацевич — на 5

This commit is contained in:
2026-11-20 19:55:05 +03:00
parent 7aa4ea541b
commit 0bf67b3e84
18 changed files with 1421 additions and 168 deletions
+5 -1
View File
@@ -16,7 +16,11 @@ class HealthOut(BaseModel):
@router.get("/health/live", response_model=HealthOut)
async def live() -> dict:
async def live(request: Request) -> dict:
# Для httpchk HAProxy: процесс принимает работу. Redis/Postgres здесь не смотрим,
# иначе при отказе Redis касса выкинет ВСЕ реплики и /users/me не сможет отдать 401.
if not getattr(request.app.state, "accepting", False):
raise AppError(503, "unavailable", "Сервер останавливается")
return {"status": "ok"}
+19 -5
View File
@@ -1,10 +1,13 @@
import asyncio
import hashlib
import re
from uuid import UUID, uuid4
from sqlalchemy import select
from sqlalchemy import select, text
from sqlalchemy.exc import IntegrityError
from app.db import map_integrity, session_scope
from app.errors import AppError
from app.models import User
from app.present import PublicUser
from app.security import hash_password, verify_password
@@ -26,14 +29,25 @@ async def get_user(user_id: UUID) -> PublicUser | None:
return PublicUser(id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at)
def _username_lock(username: str) -> tuple[int, int]:
digest = hashlib.sha256(("register:" + username).encode("utf-8")).digest()
return int.from_bytes(digest[:4], "big", signed=True), int.from_bytes(digest[4:8], "big", signed=True)
async def create_user(username: str, display_name: str, password: str) -> PublicUser:
# Argon2 считается до открытия транзакции, чтобы не держать соединение пула.
password_hash = hash_password(password)
# Argon2 в потоке: иначе 16 параллельных hash блокируют event loop,
# /health/ready не отвечает, HAProxy снимает реплику и клиент видит 503.
password_hash = await asyncio.to_thread(hash_password, password)
user_id = uuid4()
created_at = utcnow()
lock_a, lock_b = _username_lock(username)
async with session_scope() as session:
try:
async with session.begin():
await session.execute(text("SELECT pg_advisory_xact_lock(:a, :b)"), {"a": lock_a, "b": lock_b})
taken = await session.scalar(select(User.id).where(User.username == username))
if taken is not None:
raise AppError(409, "conflict", "Имя пользователя занято")
session.add(
User(
id=user_id,
@@ -51,7 +65,7 @@ async def create_user(username: str, display_name: str, password: str) -> Public
async def authenticate(username: str, password: str) -> PublicUser | None:
if _USERNAME.fullmatch(username) is None or not 12 <= len(password) <= 128:
verify_password("rejected-credential", None)
await asyncio.to_thread(verify_password, "rejected-credential", None)
return None
async with session_scope() as session:
async with session.begin():
@@ -73,6 +87,6 @@ async def authenticate(username: str, password: str) -> PublicUser | None:
display_name=row.display_name,
created_at=row.created_at,
)
if not verify_password(password, stored):
if not await asyncio.to_thread(verify_password, password, stored):
return None
return snapshot