Compare commits

..
1 Commits
12 changed files with 21 additions and 17 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
- Автор, группа: Никифорова Екатерина, БВТ2301
- Целевая оценка: **5**, выбранный трек 5: **Трек 2 «План запроса и восстановление»** (уровни 3 и 4 тоже выполнены)
- Commit/PR: #64
- Commit/PR: ЗАПОЛНИТЬ после публикации
- Источники, библиотеки и помощь ИИ: FastAPI 0.115 + Uvicorn 0.30 (как в lab1), psycopg 3.2 + psycopg_pool, argon2-cffi, redis-py; документация PostgreSQL (transactions, EXPLAIN), Valkey persistence, RFC 7617.
## Запуск из чистого clone
+3 -5
View File
@@ -1,7 +1,6 @@
"""Непрозрачный keyset-курсор (created_at, id), привязанный к ресурсу."""
import base64
import json
import uuid
from datetime import datetime, timezone
from .errors import bad_request
@@ -13,9 +12,8 @@ def encode(kind, scope, created_at, row_id):
def decode(value, kind, scope):
"""Возвращает (created_at, id). Чужой чат/пользователь/вид курсора, пустая строка или мусор -> 400."""
if not value: # пустая строка -> 400 (minLength=1 в контракте)
raise bad_request("Некорректный cursor")
"""Возвращает (created_at, id_str). Чужой чат/пользователь/вид курсора или мусор -> 400."""
import uuid
try:
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
payload = json.loads(raw.decode("utf-8"))
@@ -25,4 +23,4 @@ def decode(value, kind, scope):
raise ValueError("scope mismatch")
return created_at, row_id
except (ValueError, KeyError, TypeError, UnicodeDecodeError):
raise bad_request("Некорректный cursor")
raise bad_request("Некорректный cursor")
+9 -7
View File
@@ -1,9 +1,14 @@
"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш (cache-aside).
Чтение: кэш -> (промах) -> PostgreSQL -> наполнение кэша с TTL = min(SESSION_CACHE_TTL, остаток жизни).
Отзыв: DELETE в PostgreSQL (commit) -> tombstone в кэше (SET), чтобы медленный параллельный reader
не воскресил сессию через SET NX. Потеря/сброс кэша ничего не ломает: данные берутся из PostgreSQL.
"""
import json
import time
from datetime import timezone
from . import cache, config, db, security
from .errors import ApiError
TOMBSTONE = "revoked"
_KEY = "sess:v1:"
@@ -75,10 +80,7 @@ def lookup(token):
def revoke(digest):
if config.CACHE_URL:
wrote = cache.set_always(_KEY + digest.hex(), TOMBSTONE, config.SESSION_CACHE_TTL_SECONDS * 1000)
if not wrote:
# Контракт logout нарушен: без tombstone кэш может вернуть отозванную сессию.
raise ApiError(503, "unavailable", "Сервис временно недоступен")
with db.connection() as conn:
conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
# Только ПОСЛЕ commit: иначе читатель мог бы заново закэшировать ещё живую сессию.
cache.set_always(_KEY + digest.hex(), TOMBSTONE, config.SESSION_CACHE_TTL_SECONDS * 1000)
+3 -1
View File
@@ -13,8 +13,10 @@ x-app-env: &app-env
CACHE_URL_FILE: /run/secrets/cache_url
services:
postgres:
postgres: # источник истины: users/chats/members/messages/sessions
image: postgres:17.6-alpine
ports:
- "127.0.0.1:5433:5432" # временно открыт для track2_indexes.py
restart: unless-stopped
environment:
POSTGRES_DB: messenger
+5 -3
View File
@@ -211,15 +211,17 @@ def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw
chat = repo.create_chat(conn, auth.user_id, title, members)
return repo.chat_json(chat)
@app.get("/api/v1/chats")
def list_chats(request: Request, auth: Auth = Depends(authenticated)):
limit = validation.limit_param(request.query_params)
raw = request.query_params.get("cursor")
after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None
after = cursor.decode(raw, "chats", auth.user_id) if raw else None
with db.connection() as conn:
items, nxt = repo.list_chats(conn, auth.user_id, after, limit)
return {"items": items, "next_cursor": nxt}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, auth: Auth = Depends(authenticated)):
cid = validation.require_uuid(chat_id, "chat_id")
@@ -249,9 +251,9 @@ def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authentic
cid = validation.require_uuid(chat_id, "chat_id")
limit = validation.limit_param(request.query_params)
raw = request.query_params.get("cursor")
after = cursor.decode(raw, "messages", cid) if raw is not None else None
after = cursor.decode(raw, "messages", cid) if raw else None
with db.connection() as conn:
if not repo.is_member(conn, cid, auth.user_id):
raise not_found()
items, nxt = repo.list_messages(conn, cid, after, limit)
return {"items": items, "next_cursor": nxt}
return {"items": items, "next_cursor": nxt}
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File