ЛР 2: PostgreSQL, сессии и Valkey — на 4
Student application / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-23 18:17:09 +03:00
parent 65003b6119
commit 18b419cda2
60 changed files with 1838 additions and 14 deletions
+1
View File
@@ -0,0 +1 @@
+55
View File
@@ -0,0 +1,55 @@
import json
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from threading import BoundedSemaphore, Lock
from time import monotonic
import redis
from src.config import secret
cache = redis.Redis.from_url(secret("CACHE_URL"), decode_responses=True,
socket_connect_timeout=0.2, socket_timeout=0.2,
retry_on_timeout=False, max_connections=4)
CACHE_TTL = 60
# A socket timeout alone does not bound DNS resolution when the container is down.
# Bound the complete optional operation and the number of pending worker tasks.
workers = ThreadPoolExecutor(max_workers=4, thread_name_prefix="profile-cache")
slots = BoundedSemaphore(4)
state_lock = Lock()
unavailable_until = 0.0
def optional_call(method, *args, **kwargs):
global unavailable_until
with state_lock:
if monotonic() < unavailable_until:
return None
if not slots.acquire(blocking=False):
return None
future = workers.submit(method, *args, **kwargs)
future.add_done_callback(lambda _: slots.release())
try:
return future.result(timeout=0.25)
except (redis.RedisError, TimeoutError):
with state_lock:
unavailable_until = monotonic() + 5
future.cancel()
return None
def profile(user_id, load):
# Profiles are immutable in this API. Session validity is ALWAYS checked in PG.
# Only public fields are cached, never passwords, hashes or bearer tokens.
key = "profile:" + user_id
value = optional_call(cache.get, key)
if value:
try:
data = json.loads(value)
if data.get("id") == user_id and set(data) == {"id", "username", "display_name", "created_at"}:
return data
except (ValueError, TypeError, AttributeError):
pass
data = load()
if data:
optional_call(cache.set, key, json.dumps(data), ex=CACHE_TTL)
return data
+16
View File
@@ -0,0 +1,16 @@
import os
from pathlib import Path
def secret(name):
path = os.environ.get(name + "_FILE")
if path:
return Path(path).read_text().strip()
raise RuntimeError(f"{name}_FILE is required")
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if not 1 <= SESSION_TTL <= 604800:
raise RuntimeError("SESSION_TTL_SECONDS must be 1..604800")
if os.getenv("SESSION_STORE", "postgres") != "postgres":
raise RuntimeError("This implementation uses PostgreSQL sessions")
+40
View File
@@ -0,0 +1,40 @@
from contextlib import contextmanager
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from src.config import secret
pool = ConnectionPool(
conninfo=secret("DATABASE_URL"), min_size=1, max_size=8,
timeout=2, max_waiting=32, reconnect_timeout=5, open=False,
kwargs={"connect_timeout": 2, "row_factory": dict_row,
"options": "-c statement_timeout=2000 -c lock_timeout=1500 -c idle_in_transaction_session_timeout=5000 -c timezone=UTC"},
)
def migrate():
# One transaction + advisory lock serializes concurrent API bootstraps.
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=3) as conn:
conn.execute("SET LOCAL lock_timeout = '10s'")
conn.execute("SET LOCAL statement_timeout = '15s'")
conn.execute("SELECT pg_advisory_xact_lock(202602)")
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
for path in sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")):
if not conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone():
conn.execute(path.read_text())
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,))
@contextmanager
def connection():
with pool.connection() as conn:
# psycopg context commits on success, rolls back on EVERY exception.
yield conn
if __name__ == "__main__":
migrate()
print("PASS: versioned migrations applied (already applied versions skipped)")
+34
View File
@@ -0,0 +1,34 @@
from fastapi import Request
from fastapi.responses import JSONResponse
class ApiError(Exception):
def __init__(
self,
status_code: int,
code: str,
message: str,
):
self.status_code = status_code
self.code = code
self.message = message
def error_response(
request: Request,
status_code: int,
code: str,
message: str,
) -> JSONResponse:
request_id = request.state.request_id
return JSONResponse(
status_code=status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
)
+160
View File
@@ -0,0 +1,160 @@
import hashlib
import logging
import secrets
from contextlib import asynccontextmanager
from uuid import UUID, uuid4
import anyio
import psycopg
from fastapi import Depends, FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from psycopg_pool import PoolTimeout, TooManyRequests
from starlette.exceptions import HTTPException
from src import store
from src.cache import profile
from src.config import SESSION_TTL
from src.db import connection, migrate, pool
from src.errors import ApiError, error_response
from src.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Message, MessagePage, User
from src.security import basic_credentials, hasher, token_hash, unauthorized, verify
@asynccontextmanager
async def lifespan(app):
# Startup happens before serving requests; migrations also work via python -m src.db.
anyio.to_thread.current_default_thread_limiter().total_tokens = 16
migrate()
pool.open()
pool.wait(timeout=10)
yield
pool.close()
app = FastAPI(title="MTUSI Messenger", version="1.2.0", lifespan=lifespan,
docs_url=None, redoc_url=None, openapi_url=None)
def failure(request, status, code, message):
response = error_response(request, status, code, message)
if status == 401:
basic = request.url.path == "/api/v1/auth/sessions"
response.headers['WWW-Authenticate'] = ('Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"')
return response
@app.middleware("http")
async def request_context(request, call_next):
request.state.request_id = str(uuid4())
try:
if request.method == "POST" and request.url.path == "/api/v1/auth/sessions" and await request.body():
raise ApiError(400, "invalid_request", "Вход не принимает тело запроса")
response = await call_next(request)
except ApiError as exc:
response = failure(request, exc.status_code, exc.code, exc.message)
except (psycopg.Error, PoolTimeout, TooManyRequests):
response = failure(request, 503, "unavailable", "Хранилище временно недоступно")
except Exception as exc:
logging.error("Unhandled request error: %s", type(exc).__name__)
response = failure(request, 500, "internal_error", "Внутренняя ошибка сервера")
response.headers['X-Request-Id'] = request.state.request_id
return response
@app.exception_handler(ApiError)
async def api_error(request, exc):
return failure(request, exc.status_code, exc.code, exc.message)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return failure(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(HTTPException)
async def http_error(request, exc):
return failure(request, exc.status_code, "not_found" if exc.status_code == 404 else "invalid_request", "Недопустимый HTTP-запрос")
def require_user(request: Request):
digest = token_hash(request.headers.get('Authorization'))
with connection() as conn:
row = conn.execute("SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()", (digest,)).fetchone()
if row is None:
unauthorized()
user_id = str(row['user_id'])
user = profile(user_id, lambda: store.load_user(user_id))
if user is None:
unauthorized()
request.state.token_hash = digest
return User(**user)
@app.get('/health/live')
def live():
return {"status": "ok"}
@app.get('/health/ready')
def ready():
with connection() as conn:
conn.execute("SELECT 1").fetchone()
return {"status": "ok"}
@app.post('/api/v1/users', status_code=201, response_model=User)
def register(data: CreateUser):
return store.create_user(data, hasher.hash(data.password))
@app.post('/api/v1/auth/sessions', status_code=201)
def login(request: Request):
username, password = basic_credentials(request.headers.get('Authorization'))
with connection() as conn:
row = conn.execute("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=%s", (username,)).fetchone()
valid = verify(row['password_hash'] if row else None, password)
if not row or not valid:
unauthorized()
token = secrets.token_urlsafe(32)
digest = hashlib.sha256(token.encode('ascii')).digest()
with connection() as conn:
result = conn.execute("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at", (digest, row['id'], SESSION_TTL)).fetchone()
del row['password_hash']
return {"token": token, "token_type": "Bearer", "expires_at": store.public(result['expires_at']), "user": store.public(row)}
@app.delete('/api/v1/auth/sessions/current', status_code=204)
def logout(request: Request, user: User = Depends(require_user)):
with connection() as conn:
conn.execute("DELETE FROM sessions WHERE token_hash=%s", (request.state.token_hash,))
return Response(status_code=204)
@app.get('/api/v1/users/me', response_model=User)
def me(user: User = Depends(require_user)):
return user
@app.post('/api/v1/chats', status_code=201, response_model=Chat)
def create_chat(data: CreateChat, user: User = Depends(require_user)):
return store.create_chat(data, user.id)
@app.get('/api/v1/chats', response_model=ChatPage)
def chats(user: User = Depends(require_user), limit: int = Query(50, ge=1, le=100), cursor: str | None = Query(None, min_length=1, max_length=2048)):
return store.list_chats(user.id, limit, cursor)
@app.get('/api/v1/chats/{chat_id}', response_model=Chat)
def chat(chat_id: UUID, user: User = Depends(require_user)):
return store.get_chat(str(chat_id), user.id)
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201, response_model=Message)
def send(chat_id: UUID, data: CreateMessage, user: User = Depends(require_user)):
return store.create_message(str(chat_id), user.id, data.text)
@app.get('/api/v1/chats/{chat_id}/messages', response_model=MessagePage)
def history(chat_id: UUID, user: User = Depends(require_user), limit: int = Query(50, ge=1, le=100), cursor: str | None = Query(None, min_length=1, max_length=2048)):
return store.list_messages(str(chat_id), user.id, limit, cursor)
+140
View File
@@ -0,0 +1,140 @@
from pydantic import BaseModel, ConfigDict, Field, field_validator
from uuid import UUID
class CreateUser(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
)
username: str = Field(
min_length=3,
max_length=32,
pattern=r"^[a-z0-9_]{3,32}$",
)
display_name: str = Field(
min_length=1,
max_length=100,
)
@field_validator("display_name")
@classmethod
def display_name_must_not_be_blank(cls, value: str) -> str:
if not value.strip() or "\x00" in value:
raise ValueError("display_name must not be blank")
return value
password: str = Field(min_length=12, max_length=128)
@field_validator("password")
@classmethod
def password_must_not_be_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("password must not be blank")
return value
class User(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
username: str
display_name: str
created_at: str
class CreateChat(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
)
title: str = Field(
min_length=1,
max_length=100,
)
member_ids: list[str] = Field(
min_length=1,
max_length=100,
)
@field_validator("title")
@classmethod
def title_must_not_be_blank(cls, value: str) -> str:
if not value.strip() or "\x00" in value:
raise ValueError("title must not be blank")
return value
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, value: list[str]) -> list[str]:
normalized = []
for member_id in value:
try:
normalized.append(str(UUID(member_id)))
except (ValueError, TypeError):
raise ValueError("member_ids must contain valid UUIDs") from None
if len(normalized) != len(set(normalized)):
raise ValueError("member_ids must be unique")
return normalized
class Chat(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
title: str
member_ids: list[str]
created_at: str
class ChatPage(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list[Chat]
next_cursor: str | None
class CreateMessage(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
)
text: str = Field(
min_length=1,
max_length=4000,
)
@field_validator("text")
@classmethod
def text_must_not_be_blank(cls, value: str) -> str:
if not value.strip() or "\x00" in value:
raise ValueError("text must not be blank")
return value
class Message(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
chat_id: str
sender_id: str
text: str
created_at: str
class MessagePage(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list[Message]
next_cursor: str | None
+74
View File
@@ -0,0 +1,74 @@
import base64
import json
import re
from datetime import datetime
from uuid import UUID
from src.errors import ApiError
def encode_cursor(
resource: str,
owner_id: str,
created_at: str,
object_id: str,
) -> str:
payload = {
"resource": resource,
"owner_id": owner_id,
"created_at": created_at,
"id": object_id,
}
raw = json.dumps(
payload,
separators=(",", ":"),
).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(
cursor: str,
expected_resource: str,
expected_owner_id: str,
) -> tuple[str, str]:
try:
if not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
raise ValueError
padding = "=" * (-len(cursor) % 4)
raw = base64.b64decode(
(cursor + padding).encode("ascii"), altchars=b"-_", validate=True
)
payload = json.loads(raw.decode("utf-8"))
if payload["resource"] != expected_resource:
raise ValueError
if payload["owner_id"] != expected_owner_id:
raise ValueError
created_at = payload["created_at"]
object_id = payload["id"]
# The cursor must carry the same UTC timestamp format produced
# by the server. Invalid timestamps must return HTTP 400 before a SQL cast.
if not isinstance(created_at, str) or not re.fullmatch(
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z",
created_at,
):
raise ValueError
datetime.fromisoformat(created_at.replace("Z", "+00:00"))
UUID(object_id)
return created_at, object_id
except Exception:
raise ApiError(
status_code=400,
code="invalid_request",
message="Некорректный cursor",
)
+47
View File
@@ -0,0 +1,47 @@
import base64
import hashlib
import re
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, InvalidHashError
from src.errors import ApiError
# Explicit bounded Argon2id parameters: 19 MiB, 2 passes, one lane.
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
DUMMY_HASH = hasher.hash(secrets.token_urlsafe(32))
def unauthorized():
raise ApiError(401, "unauthorized", "Требуется действительная сессия")
def basic_credentials(header):
try:
scheme, value = header.split(" ", 1)
if scheme.lower() != "basic":
raise ValueError
username, password = base64.b64decode(value, validate=True).decode("utf-8").split(":", 1)
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
raise ValueError
return username, password
except (ValueError, UnicodeError, AttributeError):
unauthorized()
def verify(encoded, password):
try:
return hasher.verify(encoded or DUMMY_HASH, password)
except (VerificationError, InvalidHashError):
return False
def token_hash(header):
try:
scheme, token = header.split(" ", 1)
if scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
raise ValueError
return hashlib.sha256(token.encode("ascii")).digest()
except (ValueError, AttributeError):
unauthorized()
+117
View File
@@ -0,0 +1,117 @@
from datetime import datetime
from uuid import UUID, uuid4
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from src.db import connection
from src.errors import ApiError
from src.pagination import decode_cursor, encode_cursor
def public(value):
if isinstance(value, dict):
return {key: public(item) for key, item in value.items()}
if isinstance(value, list):
return [public(item) for item in value]
if isinstance(value, UUID):
return str(value)
if isinstance(value, datetime):
return value.isoformat().replace("+00:00", "Z")
return value
def create_user(data, password_hash):
try:
with connection() as conn:
row = conn.execute(
"INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at",
(uuid4(), data.username, data.display_name, password_hash),
).fetchone()
return public(row)
except UniqueViolation:
raise ApiError(409, "conflict", "Username уже занят") from None
def load_user(user_id):
with connection() as conn:
row = conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (user_id,)).fetchone()
return public(row)
def create_chat(data, caller):
if caller not in data.member_ids:
raise ApiError(400, "invalid_request", "Создатель должен входить в member_ids")
try:
with connection() as conn:
chat = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (uuid4(), data.title)).fetchone()
# FK errors here MUST roll back the already inserted parent chat.
with conn.cursor() as cursor:
cursor.executemany("INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", [(chat['id'], member) for member in data.member_ids])
chat['member_ids'] = data.member_ids
return public(chat)
except ForeignKeyViolation:
raise ApiError(400, "invalid_request", "Указан неизвестный участник") from None
CHAT_SELECT = """SELECT c.id,c.title,c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids
FROM chats c WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)"""
def get_chat(chat_id, user_id):
with connection() as conn:
row = conn.execute(CHAT_SELECT + " AND c.id=%s", (user_id, chat_id)).fetchone()
if not row:
raise ApiError(404, "not_found", "Объект не найден")
return public(row)
def page(rows, limit, resource, owner):
items = public(rows[:limit])
cursor = None
if len(rows) > limit:
last = items[-1]
cursor = encode_cursor(resource, owner, last['created_at'], last['id'])
return {"items": items, "next_cursor": cursor}
def list_chats(user_id, limit, cursor):
params = [user_id]
sql = CHAT_SELECT
if cursor is not None:
timestamp, object_id = decode_cursor(cursor, "chats", user_id)
sql += " AND (c.created_at,c.id) > (%s::timestamptz,%s::uuid)"
params += [timestamp, object_id]
sql += " ORDER BY c.created_at,c.id LIMIT %s"
params.append(limit + 1)
with connection() as conn:
rows = conn.execute(sql, params).fetchall()
return page(rows, limit, "chats", user_id)
def create_message(chat_id, user_id, text):
with connection() as conn:
row = conn.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""",
(uuid4(), chat_id, user_id, text, chat_id, user_id)).fetchone()
if not row:
raise ApiError(404, "not_found", "Объект не найден")
return public(row)
def list_messages(chat_id, user_id, limit, cursor):
params = [chat_id]
sql = "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s"
if cursor is not None:
timestamp, object_id = decode_cursor(cursor, "messages", chat_id)
sql += " AND (created_at,id) > (%s::timestamptz,%s::uuid)"
params += [timestamp, object_id]
sql += " ORDER BY created_at,id LIMIT %s"
params.append(limit + 1)
with connection() as conn:
if not conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (chat_id, user_id)).fetchone():
raise ApiError(404, "not_found", "Объект не найден")
rows = conn.execute(sql, params).fetchall()
return page(rows, limit, "messages", chat_id)