я надеюсь я исправила поставьте зачет

This commit is contained in:
2026-10-17 01:21:46 +03:00
parent dbe0a5ea7d
commit 5e89a36878
11 changed files with 16 additions and 20 deletions
+5 -3
View File
@@ -1,6 +1,7 @@
"""Непрозрачный keyset-курсор (created_at, id), привязанный к ресурсу."""
import base64
import json
import uuid
from datetime import datetime, timezone
from .errors import bad_request
@@ -12,8 +13,9 @@ def encode(kind, scope, created_at, row_id):
def decode(value, kind, scope):
"""Возвращает (created_at, id_str). Чужой чат/пользователь/вид курсора или мусор -> 400."""
import uuid
"""Возвращает (created_at, id). Чужой чат/пользователь/вид курсора, пустая строка или мусор -> 400."""
if not value: # пустая строка -> 400 (minLength=1 в контракте)
raise bad_request("Некорректный cursor")
try:
raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
payload = json.loads(raw.decode("utf-8"))
@@ -23,4 +25,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")
+7 -9
View File
@@ -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 time
from datetime import timezone
from . import cache, config, db, security
from .errors import ApiError
TOMBSTONE = "revoked"
_KEY = "sess:v1:"
@@ -80,7 +75,10 @@ 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,))
# Только ПОСЛЕ commit: иначе читатель мог бы заново закэшировать ещё живую сессию.
cache.set_always(_KEY + digest.hex(), TOMBSTONE, config.SESSION_CACHE_TTL_SECONDS * 1000)
conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
+1 -3
View File
@@ -13,10 +13,8 @@ x-app-env: &app-env
CACHE_URL_FILE: /run/secrets/cache_url
services:
postgres: # источник истины: users/chats/members/messages/sessions
postgres:
image: postgres:17.6-alpine
ports:
- "127.0.0.1:5433:5432" # временно открыт для track2_indexes.py
restart: unless-stopped
environment:
POSTGRES_DB: messenger
+3 -5
View File
@@ -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)
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 else None
after = cursor.decode(raw, "chats", auth.user_id) if raw is not None 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")
@@ -251,9 +249,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 else None
after = cursor.decode(raw, "messages", cid) if raw is not None 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}
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File