forked from mtusi2026/mtusi2026lab2
Compare commits
2
Commits
c4ec287633
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e89a36878 | ||
|
|
dbe0a5ea7d |
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
- Автор, группа: Никифорова Екатерина, БВТ2301
|
- Автор, группа: Никифорова Екатерина, БВТ2301
|
||||||
- Целевая оценка: **5**, выбранный трек 5: **Трек 2 «План запроса и восстановление»** (уровни 3 и 4 тоже выполнены)
|
- Целевая оценка: **5**, выбранный трек 5: **Трек 2 «План запроса и восстановление»** (уровни 3 и 4 тоже выполнены)
|
||||||
- Commit/PR: ЗАПОЛНИТЬ после публикации
|
- Commit/PR: #64
|
||||||
- Источники, библиотеки и помощь ИИ: FastAPI 0.115 + Uvicorn 0.30 (как в lab1), psycopg 3.2 + psycopg_pool, argon2-cffi, redis-py; документация PostgreSQL (transactions, EXPLAIN), Valkey persistence, RFC 7617.
|
- Источники, библиотеки и помощь ИИ: FastAPI 0.115 + Uvicorn 0.30 (как в lab1), psycopg 3.2 + psycopg_pool, argon2-cffi, redis-py; документация PostgreSQL (transactions, EXPLAIN), Valkey persistence, RFC 7617.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|||||||
+4
-2
@@ -1,6 +1,7 @@
|
|||||||
"""Непрозрачный keyset-курсор (created_at, id), привязанный к ресурсу."""
|
"""Непрозрачный keyset-курсор (created_at, id), привязанный к ресурсу."""
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
|
import uuid
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from .errors import bad_request
|
from .errors import bad_request
|
||||||
@@ -12,8 +13,9 @@ def encode(kind, scope, created_at, row_id):
|
|||||||
|
|
||||||
|
|
||||||
def decode(value, kind, scope):
|
def decode(value, kind, scope):
|
||||||
"""Возвращает (created_at, id_str). Чужой чат/пользователь/вид курсора или мусор -> 400."""
|
"""Возвращает (created_at, id). Чужой чат/пользователь/вид курсора, пустая строка или мусор -> 400."""
|
||||||
import uuid
|
if not value: # пустая строка -> 400 (minLength=1 в контракте)
|
||||||
|
raise bad_request("Некорректный cursor")
|
||||||
try:
|
try:
|
||||||
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||||
payload = json.loads(raw.decode("utf-8"))
|
payload = json.loads(raw.decode("utf-8"))
|
||||||
|
|||||||
+6
-8
@@ -1,14 +1,9 @@
|
|||||||
"""Сессии: 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 json
|
||||||
import time
|
import time
|
||||||
from datetime import timezone
|
from datetime import timezone
|
||||||
|
|
||||||
from . import cache, config, db, security
|
from . import cache, config, db, security
|
||||||
|
from .errors import ApiError
|
||||||
|
|
||||||
TOMBSTONE = "revoked"
|
TOMBSTONE = "revoked"
|
||||||
_KEY = "sess:v1:"
|
_KEY = "sess:v1:"
|
||||||
@@ -80,7 +75,10 @@ def lookup(token):
|
|||||||
|
|
||||||
|
|
||||||
def revoke(digest):
|
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:
|
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)
|
|
||||||
|
|||||||
+1
-3
@@ -13,10 +13,8 @@ x-app-env: &app-env
|
|||||||
CACHE_URL_FILE: /run/secrets/cache_url
|
CACHE_URL_FILE: /run/secrets/cache_url
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres: # источник истины: users/chats/members/messages/sessions
|
postgres:
|
||||||
image: postgres:17.6-alpine
|
image: postgres:17.6-alpine
|
||||||
ports:
|
|
||||||
- "127.0.0.1:5433:5432" # временно открыт для track2_indexes.py
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_DB: messenger
|
POSTGRES_DB: messenger
|
||||||
|
|||||||
@@ -211,17 +211,15 @@ def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw
|
|||||||
chat = repo.create_chat(conn, auth.user_id, title, members)
|
chat = repo.create_chat(conn, auth.user_id, title, members)
|
||||||
return repo.chat_json(chat)
|
return repo.chat_json(chat)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/chats")
|
@app.get("/api/v1/chats")
|
||||||
def list_chats(request: Request, auth: Auth = Depends(authenticated)):
|
def list_chats(request: Request, auth: Auth = Depends(authenticated)):
|
||||||
limit = validation.limit_param(request.query_params)
|
limit = validation.limit_param(request.query_params)
|
||||||
raw = request.query_params.get("cursor")
|
raw = request.query_params.get("cursor")
|
||||||
after = cursor.decode(raw, "chats", auth.user_id) if raw else None
|
after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None
|
||||||
with db.connection() as conn:
|
with db.connection() as conn:
|
||||||
items, nxt = repo.list_chats(conn, auth.user_id, after, limit)
|
items, nxt = repo.list_chats(conn, auth.user_id, after, limit)
|
||||||
return {"items": items, "next_cursor": nxt}
|
return {"items": items, "next_cursor": nxt}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/chats/{chat_id}")
|
@app.get("/api/v1/chats/{chat_id}")
|
||||||
def get_chat(chat_id: str, auth: Auth = Depends(authenticated)):
|
def get_chat(chat_id: str, auth: Auth = Depends(authenticated)):
|
||||||
cid = validation.require_uuid(chat_id, "chat_id")
|
cid = validation.require_uuid(chat_id, "chat_id")
|
||||||
@@ -251,7 +249,7 @@ def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authentic
|
|||||||
cid = validation.require_uuid(chat_id, "chat_id")
|
cid = validation.require_uuid(chat_id, "chat_id")
|
||||||
limit = validation.limit_param(request.query_params)
|
limit = validation.limit_param(request.query_params)
|
||||||
raw = request.query_params.get("cursor")
|
raw = request.query_params.get("cursor")
|
||||||
after = cursor.decode(raw, "messages", cid) if raw else None
|
after = cursor.decode(raw, "messages", cid) if raw is not None else None
|
||||||
with db.connection() as conn:
|
with db.connection() as conn:
|
||||||
if not repo.is_member(conn, cid, auth.user_id):
|
if not repo.is_member(conn, cid, auth.user_id):
|
||||||
raise not_found()
|
raise not_found()
|
||||||
|
|||||||
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Reference in New Issue
Block a user