forked from mtusi2026/mtusi2026lab2
Лабораторная работа 2
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"""Конфигурация из переменных окружения.
|
||||
|
||||
Секреты (строки подключения с паролями) читаются из файлов *_FILE,
|
||||
которые Compose монтирует как secrets в /run/secrets/. Для локального
|
||||
запуска без Docker допускаются и прямые переменные DATABASE_URL / CACHE_URL.
|
||||
"""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _read_secret(name: str) -> Optional[str]:
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
value = handle.read().strip()
|
||||
return value or None
|
||||
value = os.environ.get(name, "").strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def _int(name: str, default: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
return int(raw)
|
||||
|
||||
|
||||
def _float(name: str, default: float) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
return float(raw)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
app_env: str
|
||||
database_url: str
|
||||
cache_url: Optional[str]
|
||||
session_store: str
|
||||
session_ttl_seconds: int
|
||||
session_cache_ttl_seconds: int
|
||||
db_pool_min: int
|
||||
db_pool_max: int
|
||||
db_pool_timeout: float
|
||||
db_connect_timeout: int
|
||||
db_statement_timeout_ms: int
|
||||
cache_timeout_seconds: float
|
||||
cache_retry_after_seconds: float
|
||||
migrate_wait_seconds: int
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
database_url = _read_secret("DATABASE_URL")
|
||||
if not database_url:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE must be set")
|
||||
|
||||
ttl = _int("SESSION_TTL_SECONDS", 3600)
|
||||
if ttl < 1:
|
||||
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
|
||||
|
||||
session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower()
|
||||
# Источник истины для сессий в этой реализации всегда PostgreSQL;
|
||||
# Redis (CACHE_URL) — только кэш проверок токена.
|
||||
if session_store != "postgres":
|
||||
raise RuntimeError("only SESSION_STORE=postgres is supported")
|
||||
|
||||
return Settings(
|
||||
app_env=os.environ.get("APP_ENV", "lab"),
|
||||
database_url=database_url,
|
||||
cache_url=_read_secret("CACHE_URL"),
|
||||
session_store=session_store,
|
||||
session_ttl_seconds=ttl,
|
||||
session_cache_ttl_seconds=_int("SESSION_CACHE_TTL_SECONDS", 60),
|
||||
db_pool_min=_int("DB_POOL_MIN", 1),
|
||||
db_pool_max=_int("DB_POOL_MAX", 10),
|
||||
db_pool_timeout=_float("DB_POOL_TIMEOUT_SECONDS", 3.0),
|
||||
db_connect_timeout=_int("DB_CONNECT_TIMEOUT_SECONDS", 3),
|
||||
db_statement_timeout_ms=_int("DB_STATEMENT_TIMEOUT_MS", 5000),
|
||||
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.25),
|
||||
cache_retry_after_seconds=_float("CACHE_RETRY_AFTER_SECONDS", 5.0),
|
||||
migrate_wait_seconds=_int("MIGRATE_WAIT_SECONDS", 60),
|
||||
)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Пул соединений PostgreSQL и версионируемые миграции."""
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .config import Settings
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
|
||||
|
||||
# Произвольная константа: один процесс за раз применяет миграции,
|
||||
# даже если одновременно стартуют несколько реплик API (lab3).
|
||||
MIGRATION_LOCK_ID = 2026_0002
|
||||
|
||||
|
||||
def conninfo_kwargs(settings: Settings) -> dict:
|
||||
return {
|
||||
"connect_timeout": settings.db_connect_timeout,
|
||||
# Все timestamptz приходят в UTC; любой запрос ограничен по времени.
|
||||
"options": "-c TimeZone=UTC -c statement_timeout=%d"
|
||||
% settings.db_statement_timeout_ms,
|
||||
"application_name": "messenger-api",
|
||||
}
|
||||
|
||||
|
||||
def create_pool(settings: Settings) -> ConnectionPool:
|
||||
pool = ConnectionPool(
|
||||
conninfo=settings.database_url,
|
||||
kwargs=conninfo_kwargs(settings),
|
||||
min_size=settings.db_pool_min,
|
||||
max_size=settings.db_pool_max,
|
||||
# Сколько запрос ждёт свободное соединение, прежде чем получить 503.
|
||||
timeout=settings.db_pool_timeout,
|
||||
# Битые после рестарта БД соединения отбрасываются при выдаче из пула.
|
||||
check=ConnectionPool.check_connection,
|
||||
max_idle=300,
|
||||
reconnect_timeout=3600,
|
||||
open=False,
|
||||
name="messenger",
|
||||
)
|
||||
# wait=False: процесс поднимается, даже если БД ещё/уже недоступна;
|
||||
# readiness это покажет, а запросы получат 503.
|
||||
pool.open(wait=False)
|
||||
return pool
|
||||
|
||||
|
||||
def _migration_files():
|
||||
files = sorted(MIGRATIONS_DIR.glob("*.sql"))
|
||||
if not files:
|
||||
raise RuntimeError("no migrations found in %s" % MIGRATIONS_DIR)
|
||||
return files
|
||||
|
||||
|
||||
def apply_migrations(settings: Settings) -> list:
|
||||
"""Применяет недостающие миграции; возвращает список применённых версий."""
|
||||
applied_now = []
|
||||
with psycopg.connect(
|
||||
settings.database_url, autocommit=True, **conninfo_kwargs(settings)
|
||||
) as conn:
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK_ID,))
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
done = {
|
||||
row[0]
|
||||
for row in conn.execute("SELECT version FROM schema_migrations")
|
||||
}
|
||||
for path in _migration_files():
|
||||
version = path.stem
|
||||
if version in done:
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
# DDL и отметка о версии — одна транзакция: либо всё, либо ничего.
|
||||
with conn.transaction():
|
||||
conn.execute(sql)
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
||||
(version,),
|
||||
)
|
||||
applied_now.append(version)
|
||||
log.info("applied migration %s", version)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK_ID,))
|
||||
return applied_now
|
||||
|
||||
|
||||
def wait_and_migrate(settings: Settings) -> list:
|
||||
deadline = time.monotonic() + settings.migrate_wait_seconds
|
||||
last_error: Optional[Exception] = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
return apply_migrations(settings)
|
||||
except psycopg.OperationalError as exc:
|
||||
last_error = exc
|
||||
log.warning("database not ready for migrations, retrying")
|
||||
time.sleep(1)
|
||||
raise RuntimeError("database unavailable for migrations") from last_error
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable, Dict, Optional, Tuple
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import psycopg
|
||||
from fastapi import Depends, FastAPI, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg_pool import PoolTimeout
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from .config import load_settings
|
||||
from .db import create_pool, wait_and_migrate
|
||||
from .models import (
|
||||
Chat,
|
||||
ChatCreate,
|
||||
ChatPage,
|
||||
Message,
|
||||
MessageCreate,
|
||||
MessagePage,
|
||||
Session,
|
||||
User,
|
||||
UserCreate,
|
||||
)
|
||||
from .security import hash_password, parse_basic, parse_bearer, verify_password
|
||||
from .sessions import SessionCache, SessionService
|
||||
from .storage import Storage, UnknownMember, UsernameTaken
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
log = logging.getLogger("messenger.api")
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
settings = load_settings()
|
||||
applied = wait_and_migrate(settings)
|
||||
log.info("migrations applied at startup: %s", applied or "none")
|
||||
pool = create_pool(settings)
|
||||
storage = Storage(pool)
|
||||
cache = SessionCache(settings)
|
||||
app.state.settings = settings
|
||||
app.state.storage = storage
|
||||
app.state.cache = cache
|
||||
app.state.sessions = SessionService(storage, cache, settings)
|
||||
log.info(
|
||||
"started: session_ttl=%ss cache=%s pool=%s..%s",
|
||||
settings.session_ttl_seconds,
|
||||
"redis" if cache.client is not None else "disabled",
|
||||
settings.db_pool_min,
|
||||
settings.db_pool_max,
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
pool.close()
|
||||
if cache.client is not None:
|
||||
cache.client.close()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger (PostgreSQL + Redis)",
|
||||
version="2.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
# Request ID
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next: Callable):
|
||||
incoming = request.headers.get("X-Request-Id", "")
|
||||
request_id = incoming if REQUEST_ID_RE.match(incoming) else str(uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
|
||||
|
||||
# errors
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status_code: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def unauthorized(challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
return ApiError(401, "unauthorized", "Authentication required", {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def bad_request(message: str = "Invalid request") -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "Not found")
|
||||
|
||||
|
||||
def error_response(
|
||||
request: Request,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", None) or str(uuid4())
|
||||
all_headers = {"X-Request-Id": request_id}
|
||||
all_headers.update(headers or {})
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=all_headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
return error_response(request, 400, "invalid_request", "Invalid request")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
status_to_code = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
}
|
||||
status_code = exc.status_code if exc.status_code in status_to_code else 500
|
||||
code = status_to_code.get(status_code, "internal_error")
|
||||
message = str(exc.detail) if status_code != 500 else "Internal server error"
|
||||
return error_response(request, status_code, code, message)
|
||||
|
||||
|
||||
async def dependency_unavailable(request: Request, exc: Exception) -> JSONResponse:
|
||||
# Наружу — только общий 503, без SQL, адресов и текста драйвера.
|
||||
log.warning("database unavailable: %s", type(exc).__name__)
|
||||
return error_response(request, 503, "unavailable", "Service temporarily unavailable")
|
||||
|
||||
|
||||
app.add_exception_handler(psycopg.OperationalError, dependency_unavailable)
|
||||
app.add_exception_handler(psycopg.InterfaceError, dependency_unavailable)
|
||||
app.add_exception_handler(PoolTimeout, dependency_unavailable)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
log.exception("unexpected error")
|
||||
return error_response(request, 500, "internal_error", "Internal server error")
|
||||
|
||||
|
||||
# helpers
|
||||
|
||||
def require_json_content_type(request: Request) -> None:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if not content_type.lower().startswith("application/json"):
|
||||
raise ApiError(415, "unsupported_media_type", "Unsupported media type")
|
||||
|
||||
|
||||
def ensure_not_blank(value: str) -> None:
|
||||
if not value.strip():
|
||||
raise bad_request()
|
||||
|
||||
|
||||
def storage_of(request: Request) -> Storage:
|
||||
return request.app.state.storage
|
||||
|
||||
|
||||
def current_user(request: Request) -> User:
|
||||
"""Только Authorization: Bearer. Basic и X-User-Id здесь не дают доступа."""
|
||||
token = parse_bearer(request.headers.get("Authorization"))
|
||||
if token is None:
|
||||
raise unauthorized()
|
||||
user = request.app.state.sessions.resolve(token)
|
||||
if user is None:
|
||||
raise unauthorized()
|
||||
request.state.token = token
|
||||
return user
|
||||
|
||||
|
||||
def encode_cursor(resource_id: UUID, created_at: datetime, item_id: UUID) -> str:
|
||||
payload = {
|
||||
"resource_id": str(resource_id),
|
||||
"created_at": created_at.isoformat(),
|
||||
"item_id": str(item_id),
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor: Optional[str], expected_resource_id: UUID) -> Optional[Tuple[datetime, UUID]]:
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
padding = "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(cursor + padding)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
resource_id = UUID(payload["resource_id"])
|
||||
created_at = datetime.fromisoformat(payload["created_at"])
|
||||
item_id = UUID(payload["item_id"])
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("invalid_cursor")
|
||||
except (ValueError, KeyError, TypeError, AttributeError, json.JSONDecodeError):
|
||||
raise bad_request("Invalid cursor")
|
||||
if resource_id != expected_resource_id:
|
||||
raise bad_request("Invalid cursor")
|
||||
return created_at, item_id
|
||||
|
||||
|
||||
# health
|
||||
|
||||
@app.get("/health/live", response_model=Dict[str, str])
|
||||
def liveness() -> Dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Dict[str, str])
|
||||
def readiness(request: Request) -> Dict[str, str]:
|
||||
# Критична только PostgreSQL. Redis — кэш с обходом, его отказ не делает
|
||||
# API неготовым (см. REPORT.md).
|
||||
try:
|
||||
storage_of(request).ping()
|
||||
except (psycopg.Error, PoolTimeout):
|
||||
raise ApiError(503, "unavailable", "Database is not available")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# users
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
def register_user(request: Request, data: UserCreate) -> User:
|
||||
require_json_content_type(request)
|
||||
ensure_not_blank(data.display_name)
|
||||
ensure_not_blank(data.password)
|
||||
password_hash = hash_password(data.password)
|
||||
try:
|
||||
return storage_of(request).create_user(data.username, data.display_name, password_hash)
|
||||
except UsernameTaken:
|
||||
raise ApiError(409, "conflict", "Username already exists")
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
def get_current_user(user: User = Depends(current_user)) -> User:
|
||||
return user
|
||||
|
||||
|
||||
# sessions
|
||||
|
||||
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
|
||||
def create_session(request: Request) -> Session:
|
||||
credentials = parse_basic(request.headers.get("Authorization"))
|
||||
if credentials is None:
|
||||
raise unauthorized(BASIC_CHALLENGE)
|
||||
username, password = credentials
|
||||
found = storage_of(request).get_credentials(username)
|
||||
user, password_hash = found if found else (None, None)
|
||||
# verify_password выполняется и для несуществующего username (с хешем-пустышкой).
|
||||
if not verify_password(password_hash, password) or user is None:
|
||||
raise unauthorized(BASIC_CHALLENGE)
|
||||
token, expires_at = request.app.state.sessions.create(user)
|
||||
return Session(token=token, token_type="Bearer", expires_at=expires_at, user=user)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def delete_current_session(request: Request, user: User = Depends(current_user)) -> Response:
|
||||
if not request.app.state.sessions.revoke(request.state.token):
|
||||
raise unauthorized()
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# chats
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
def create_chat(request: Request, data: ChatCreate, user: User = Depends(current_user)) -> Chat:
|
||||
require_json_content_type(request)
|
||||
ensure_not_blank(data.title)
|
||||
if len(data.member_ids) != len(set(data.member_ids)):
|
||||
raise bad_request("Duplicate member ids")
|
||||
if user.id not in data.member_ids:
|
||||
raise bad_request("Caller must be a chat member")
|
||||
try:
|
||||
return storage_of(request).create_chat(data.title, data.member_ids)
|
||||
except UnknownMember:
|
||||
raise bad_request("Unknown member")
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
) -> ChatPage:
|
||||
after = decode_cursor(cursor, user.id)
|
||||
items, has_more = storage_of(request).list_user_chats(user.id, limit, after)
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
next_cursor = encode_cursor(user.id, items[-1].created_at, items[-1].id)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(request: Request, chat_id: UUID, user: User = Depends(current_user)) -> Chat:
|
||||
chat = storage_of(request).get_chat_for_member(chat_id, user.id)
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
# messages
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
def create_message(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
data: MessageCreate,
|
||||
user: User = Depends(current_user),
|
||||
) -> Message:
|
||||
require_json_content_type(request)
|
||||
ensure_not_blank(data.text)
|
||||
message = storage_of(request).create_message(chat_id, user.id, data.text)
|
||||
if message is None:
|
||||
raise not_found()
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
) -> MessagePage:
|
||||
after = decode_cursor(cursor, chat_id)
|
||||
result = storage_of(request).list_messages(chat_id, user.id, limit, after)
|
||||
if result is None:
|
||||
raise not_found()
|
||||
items, has_more = result
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
next_cursor = encode_cursor(chat_id, items[-1].created_at, items[-1].id)
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Ручной запуск миграций: python -m src.migrate
|
||||
|
||||
API применяет миграции и сам при старте; команда нужна для явного bootstrap
|
||||
и для демонстрации, что повторный запуск ничего не меняет.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from .config import load_settings
|
||||
from .db import wait_and_migrate
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
||||
applied = wait_and_migrate(load_settings())
|
||||
if applied:
|
||||
print("applied migrations: " + ", ".join(applied))
|
||||
else:
|
||||
print("schema is up to date; nothing applied")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class UserCreate(StrictModel):
|
||||
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,
|
||||
)
|
||||
# lab2: пароль обязателен; длина в Unicode code points (len() в Python).
|
||||
password: str = Field(
|
||||
min_length=12,
|
||||
max_length=128,
|
||||
)
|
||||
|
||||
|
||||
class User(StrictModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Session(StrictModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
|
||||
class ChatCreate(StrictModel):
|
||||
title: str = Field(
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
)
|
||||
member_ids: List[UUID] = Field(
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
)
|
||||
|
||||
|
||||
class Chat(StrictModel):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: List[UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class MessageCreate(StrictModel):
|
||||
text: str = Field(
|
||||
min_length=1,
|
||||
max_length=4000,
|
||||
)
|
||||
|
||||
|
||||
class Message(StrictModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ChatPage(StrictModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
|
||||
class MessagePage(StrictModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str]
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Пароли, разбор Basic/Bearer и генерация токенов."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
# Argon2id (библиотека argon2-cffi). Параметры — рекомендация OWASP для
|
||||
# Argon2id: m=19 MiB, t=2, p=1. Пароль хешируется целиком в UTF-8, без усечения.
|
||||
_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1)
|
||||
|
||||
# Хеш-«пустышка»: проверка для несуществующего пользователя стоит столько же,
|
||||
# сколько для существующего, — время ответа не выдаёт наличие username.
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing-equalization")
|
||||
|
||||
# 32 байта случайности = 256 бит энтропии; base64url без padding = 43 символа.
|
||||
TOKEN_BYTES = 32
|
||||
MAX_TOKEN_LENGTH = 256
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: Optional[str], password: str) -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash or _DUMMY_HASH, password) and bool(
|
||||
password_hash
|
||||
)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(TOKEN_BYTES)
|
||||
|
||||
|
||||
def token_digest(token: str) -> bytes:
|
||||
"""Токен высокоэнтропийный, поэтому для поиска достаточно быстрого SHA-256.
|
||||
|
||||
В отличие от пароля, перебор 256-битного токена невозможен, и KDF здесь
|
||||
только замедлил бы каждый запрос.
|
||||
"""
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def parse_basic(header: Optional[str]) -> Optional[Tuple[str, str]]:
|
||||
"""Authorization: Basic base64(username:password) -> (username, password)."""
|
||||
if not header:
|
||||
return None
|
||||
scheme, _, value = header.strip().partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(value.strip(), validate=True)
|
||||
decoded = raw.decode("utf-8")
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
return None
|
||||
username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо
|
||||
if not sep or not USERNAME_RE.match(username):
|
||||
return None
|
||||
if not 12 <= len(password) <= 128:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: Optional[str]) -> Optional[str]:
|
||||
if not header:
|
||||
return None
|
||||
scheme, _, value = header.strip().partition(" ")
|
||||
token = value.strip()
|
||||
if scheme.lower() != "bearer" or not token or len(token) > MAX_TOKEN_LENGTH:
|
||||
return None
|
||||
if not token.isascii() or any(ch.isspace() for ch in token):
|
||||
return None
|
||||
return token
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
"""Сессии: PostgreSQL — источник истины, Redis — кэш проверок токена.
|
||||
|
||||
Роль Redis
|
||||
----------
|
||||
Каждый защищённый запрос сначала ищет `sess:<sha256(token)>` в Redis.
|
||||
* попадание -> пользователь берётся из кэша, PostgreSQL не трогаем;
|
||||
* промах -> читаем sessions JOIN users в PostgreSQL и кладём результат
|
||||
в Redis через SET NX с TTL = min(SESSION_CACHE_TTL_SECONDS,
|
||||
время до expires_at). Запись кэша никогда не переживает сессию.
|
||||
|
||||
Инвалидация (logout)
|
||||
--------------------
|
||||
1. UPDATE sessions SET revoked_at (COMMIT в PostgreSQL — момент отзыва);
|
||||
2. SET sess:<hash> = "revoked" PX=SESSION_CACHE_TTL (обычный SET, перезаписывает).
|
||||
Заполнение кэша идёт через SET NX, поэтому параллельный запрос, прочитавший
|
||||
сессию до отзыва, не может перезаписать «надгробие» валидной записью.
|
||||
|
||||
Отказ Redis
|
||||
-----------
|
||||
Любая ошибка Redis (таймаут 250 мс) -> кэш пропускается, проверка идёт в
|
||||
PostgreSQL; на CACHE_RETRY_AFTER_SECONDS Redis выключается (простой
|
||||
circuit breaker), чтобы не платить таймаут на каждом запросе.
|
||||
Redis работает без persistence: после рестарта кэш пуст, и это безопасно —
|
||||
следующие запросы просто заполнят его из PostgreSQL.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import redis
|
||||
|
||||
from .config import Settings
|
||||
from .models import User
|
||||
from .security import new_token, token_digest
|
||||
from .storage import Storage
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
REVOKED = "revoked"
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self.ttl_ms = settings.session_cache_ttl_seconds * 1000
|
||||
self.retry_after = settings.cache_retry_after_seconds
|
||||
self._down_until = 0.0
|
||||
self._lock = threading.Lock()
|
||||
self.client: Optional[redis.Redis] = None
|
||||
if settings.cache_url:
|
||||
self.client = redis.Redis.from_url(
|
||||
settings.cache_url,
|
||||
socket_timeout=settings.cache_timeout_seconds,
|
||||
socket_connect_timeout=settings.cache_timeout_seconds,
|
||||
retry_on_timeout=False,
|
||||
health_check_interval=30,
|
||||
max_connections=20,
|
||||
decode_responses=True,
|
||||
)
|
||||
# Счётчики для наблюдения и тестов (GET /health/cache не нужен контракту,
|
||||
# поэтому они только логируются).
|
||||
self.hits = 0
|
||||
self.misses = 0
|
||||
self.errors = 0
|
||||
|
||||
@staticmethod
|
||||
def key(digest: bytes) -> str:
|
||||
return "sess:" + digest.hex()
|
||||
|
||||
def _available(self) -> bool:
|
||||
return self.client is not None and time.monotonic() >= self._down_until
|
||||
|
||||
def _failed(self, exc: Exception) -> None:
|
||||
with self._lock:
|
||||
self.errors += 1
|
||||
if time.monotonic() >= self._down_until:
|
||||
log.warning("redis unavailable (%s); bypassing cache for %.0fs",
|
||||
type(exc).__name__, self.retry_after)
|
||||
self._down_until = time.monotonic() + self.retry_after
|
||||
|
||||
def get(self, digest: bytes):
|
||||
"""None — промах/кэш недоступен; REVOKED — отозвано; иначе (User, expires_at)."""
|
||||
if not self._available():
|
||||
return None
|
||||
try:
|
||||
raw = self.client.get(self.key(digest))
|
||||
except redis.RedisError as exc:
|
||||
self._failed(exc)
|
||||
return None
|
||||
if raw is None:
|
||||
self.misses += 1
|
||||
return None
|
||||
self.hits += 1
|
||||
if raw == REVOKED:
|
||||
return REVOKED
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
expires_at = datetime.fromisoformat(data["expires_at"])
|
||||
return User(**data["user"]), expires_at
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
def put(self, digest: bytes, user: User, expires_at: datetime) -> None:
|
||||
if not self._available():
|
||||
return
|
||||
remaining_ms = int((expires_at - datetime.now(timezone.utc)).total_seconds() * 1000)
|
||||
ttl = min(self.ttl_ms, remaining_ms)
|
||||
if ttl <= 0:
|
||||
return
|
||||
value = json.dumps({"user": user.model_dump(mode="json"), "expires_at": expires_at.isoformat()})
|
||||
try:
|
||||
self.client.set(self.key(digest), value, px=ttl, nx=True)
|
||||
except redis.RedisError as exc:
|
||||
self._failed(exc)
|
||||
|
||||
def revoke(self, digest: bytes) -> None:
|
||||
if self.client is None:
|
||||
return
|
||||
try:
|
||||
self.client.set(self.key(digest), REVOKED, px=self.ttl_ms)
|
||||
except redis.RedisError as exc:
|
||||
self._failed(exc)
|
||||
|
||||
def ping(self) -> bool:
|
||||
if self.client is None:
|
||||
return False
|
||||
try:
|
||||
return bool(self.client.ping())
|
||||
except redis.RedisError:
|
||||
return False
|
||||
|
||||
|
||||
class SessionService:
|
||||
def __init__(self, storage: Storage, cache: SessionCache, settings: Settings) -> None:
|
||||
self.storage = storage
|
||||
self.cache = cache
|
||||
self.ttl = settings.session_ttl_seconds
|
||||
|
||||
def create(self, user: User) -> Tuple[str, datetime]:
|
||||
token = new_token()
|
||||
expires_at = self.storage.create_session(token_digest(token), user.id, self.ttl)
|
||||
return token, expires_at
|
||||
|
||||
def resolve(self, token: str) -> Optional[User]:
|
||||
digest = token_digest(token)
|
||||
cached = self.cache.get(digest)
|
||||
if cached == REVOKED:
|
||||
return None
|
||||
if cached is not None:
|
||||
user, expires_at = cached
|
||||
if expires_at > datetime.now(timezone.utc):
|
||||
return user
|
||||
found = self.storage.find_session(digest) # PostgreSQL недоступна -> исключение -> 503
|
||||
if found is None:
|
||||
return None
|
||||
user, expires_at = found
|
||||
self.cache.put(digest, user, expires_at)
|
||||
return user
|
||||
|
||||
def revoke(self, token: str) -> bool:
|
||||
digest = token_digest(token)
|
||||
revoked = self.storage.revoke_session(digest)
|
||||
if revoked:
|
||||
self.cache.revoke(digest)
|
||||
return revoked
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
"""Доступ к PostgreSQL. Все запросы параметризованы (%s), SQL не склеивается
|
||||
со значениями пользователя. Каждая публичная операция — одна транзакция
|
||||
(`with pool.connection()` делает COMMIT при успехе и ROLLBACK при исключении).
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from psycopg import errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .models import Chat, Message, User
|
||||
|
||||
|
||||
class UsernameTaken(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
Position = Optional[Tuple[datetime, UUID]]
|
||||
|
||||
|
||||
def _user(row) -> User:
|
||||
return User(
|
||||
id=row["id"],
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, pool: ConnectionPool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
def ping(self) -> None:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
# users
|
||||
|
||||
def create_user(self, username: str, display_name: str, password_hash: str) -> User:
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid4(), username, display_name, password_hash),
|
||||
).fetchone()
|
||||
except errors.UniqueViolation:
|
||||
# Гонку двух одинаковых регистраций решает UNIQUE(username) в БД,
|
||||
# а не проверка «SELECT, потом INSERT» в приложении.
|
||||
raise UsernameTaken()
|
||||
return _user(row)
|
||||
|
||||
def get_credentials(self, username: str) -> Optional[Tuple[User, str]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _user(row), row["password_hash"]
|
||||
|
||||
# sessions (источник истины)
|
||||
|
||||
def create_session(self, token_hash: bytes, user_id: UUID, ttl_seconds: int) -> datetime:
|
||||
with self.pool.connection() as conn:
|
||||
# Заодно убираем давно истёкшие сессии этого пользователя.
|
||||
conn.execute(
|
||||
"DELETE FROM sessions WHERE user_id = %s AND expires_at < now() - interval '1 day'",
|
||||
(user_id,),
|
||||
)
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(token_hash, user_id, ttl_seconds),
|
||||
).fetchone()
|
||||
return row[0]
|
||||
|
||||
def find_session(self, token_hash: bytes) -> Optional[Tuple[User, datetime]]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > clock_timestamp()
|
||||
""",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _user(row), row["expires_at"]
|
||||
|
||||
def revoke_session(self, token_hash: bytes) -> bool:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE sessions SET revoked_at = clock_timestamp()
|
||||
WHERE token_hash = %s
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > clock_timestamp()
|
||||
RETURNING 1
|
||||
""",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
# chats
|
||||
|
||||
def _insert_members(self, conn, chat_id: UUID, member_ids: Sequence[UUID]) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||||
[(chat_id, member_id, pos) for pos, member_id in enumerate(member_ids)],
|
||||
)
|
||||
|
||||
def create_chat(self, title: str, member_ids: Sequence[UUID]) -> Chat:
|
||||
"""Чат и все участники создаются в одной транзакции.
|
||||
|
||||
Существование участников проверяет внешний ключ chat_members.user_id:
|
||||
если хоть один id неизвестен, INSERT падает, и откатывается вся
|
||||
транзакция, включая уже вставленную строку chats и других участников.
|
||||
"""
|
||||
chat_id = uuid4()
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
created_at = conn.execute(
|
||||
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING created_at",
|
||||
(chat_id, title),
|
||||
).fetchone()[0]
|
||||
self._insert_members(conn, chat_id, member_ids)
|
||||
except errors.ForeignKeyViolation:
|
||||
raise UnknownMember()
|
||||
return Chat(id=chat_id, title=title, member_ids=list(member_ids), created_at=created_at)
|
||||
|
||||
def _members_for(self, conn, chat_ids: List[UUID]) -> dict:
|
||||
members = {chat_id: [] for chat_id in chat_ids}
|
||||
if not chat_ids:
|
||||
return members
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT chat_id, user_id FROM chat_members
|
||||
WHERE chat_id = ANY(%s) ORDER BY chat_id, position
|
||||
""",
|
||||
(chat_ids,),
|
||||
).fetchall()
|
||||
for chat_id, user_id in rows:
|
||||
members[chat_id].append(user_id)
|
||||
return members
|
||||
|
||||
def get_chat_for_member(self, chat_id: UUID, user_id: UUID) -> Optional[Chat]:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id AND m.user_id = %s
|
||||
WHERE c.id = %s
|
||||
""",
|
||||
(user_id, chat_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
members = self._members_for(conn, [row["id"]])
|
||||
return Chat(id=row["id"], title=row["title"], member_ids=members[row["id"]], created_at=row["created_at"])
|
||||
|
||||
def list_user_chats(self, user_id: UUID, limit: int, after: Position) -> Tuple[List[Chat], bool]:
|
||||
params: list = [user_id]
|
||||
keyset = ""
|
||||
if after is not None:
|
||||
keyset = "AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.user_id = %s {keyset}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""".format(keyset=keyset),
|
||||
params,
|
||||
).fetchall()
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
members = self._members_for(conn, [r["id"] for r in rows])
|
||||
chats = [
|
||||
Chat(id=r["id"], title=r["title"], member_ids=members[r["id"]], created_at=r["created_at"])
|
||||
for r in rows
|
||||
]
|
||||
return chats, has_more
|
||||
|
||||
# messages
|
||||
|
||||
def create_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Optional[Message]:
|
||||
"""Проверка членства и вставка — один оператор, без окна гонки."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.cursor(row_factory=dict_row).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, sender_id, text, chat_id, sender_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return Message(**row)
|
||||
|
||||
def list_messages(
|
||||
self, chat_id: UUID, user_id: UUID, limit: int, after: Position
|
||||
) -> Optional[Tuple[List[Message], bool]]:
|
||||
params: list = [chat_id]
|
||||
keyset = ""
|
||||
if after is not None:
|
||||
keyset = "AND (created_at, id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
member = conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
if member is None:
|
||||
return None
|
||||
# Keyset-пагинация по индексу messages_chat_created_id_idx:
|
||||
# Index Scan сразу с позиции курсора, читается limit+1 строк.
|
||||
rows = conn.cursor(row_factory=dict_row).execute(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s {keyset}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""".format(keyset=keyset),
|
||||
params,
|
||||
).fetchall()
|
||||
has_more = len(rows) > limit
|
||||
return [Message(**r) for r in rows[:limit]], has_more
|
||||
Reference in New Issue
Block a user