diff --git a/app/cursor.py b/app/cursor.py index ff0c2af..c6b3b3e 100644 --- a/app/cursor.py +++ b/app/cursor.py @@ -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") \ No newline at end of file diff --git a/app/sessions.py b/app/sessions.py index df04731..ec7e234 100644 --- a/app/sessions.py +++ b/app/sessions.py @@ -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,)) \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index ec17cf4..f7f01eb 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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 diff --git a/main.py b/main.py index 1198be9..e8bde6c 100644 --- a/main.py +++ b/main.py @@ -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} \ No newline at end of file diff --git a/scripts/backup.sh b/scripts/backup.sh old mode 100644 new mode 100755 diff --git a/scripts/evidence-restart.sh b/scripts/evidence-restart.sh old mode 100644 new mode 100755 diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh old mode 100644 new mode 100755 diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh old mode 100644 new mode 100755 diff --git a/scripts/restart.sh b/scripts/restart.sh old mode 100644 new mode 100755 diff --git a/scripts/restore-check.sh b/scripts/restore-check.sh old mode 100644 new mode 100755 diff --git a/scripts/test-expiry.sh b/scripts/test-expiry.sh old mode 100644 new mode 100755