Implement Lab 3 grade 4 messenger balancing
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""MTUSI Lab 2 API."""
|
||||
@@ -0,0 +1,19 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from .settings import load_database_url
|
||||
|
||||
|
||||
engine = create_engine(
|
||||
load_database_url(),
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
pool_timeout=3,
|
||||
pool_recycle=1800,
|
||||
pool_pre_ping=True,
|
||||
connect_args={
|
||||
"connect_timeout": 3,
|
||||
"options": "-c statement_timeout=5000",
|
||||
},
|
||||
)
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
@@ -0,0 +1,23 @@
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, code: str, message: str, status: int, challenge: str | None = None):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.status = status
|
||||
self.challenge = challenge
|
||||
|
||||
|
||||
def error_response(request: Request, code: str, message: str, status: int, challenge: str | None = None):
|
||||
request_id = getattr(request.state, "request_id", "unknown")
|
||||
headers = {"X-Request-Id": request_id, "Cache-Control": "no-store"}
|
||||
if challenge:
|
||||
headers["WWW-Authenticate"] = challenge
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
headers=headers,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Create 10,000 disposable rows and record the indexed keyset-page plan."""
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from .db import engine
|
||||
|
||||
|
||||
def run() -> None:
|
||||
user_id = uuid.uuid4()
|
||||
chat_id = uuid.uuid4()
|
||||
plan_json = None
|
||||
with engine.connect() as connection:
|
||||
transaction = connection.begin()
|
||||
try:
|
||||
connection.execute(
|
||||
text("INSERT INTO users(id, username, display_name, password_hash) "
|
||||
"VALUES (:id, :username, 'Synthetic plan fixture', 'not-a-login-hash')"),
|
||||
{"id": user_id, "username": "plan_" + uuid.uuid4().hex[:20]},
|
||||
)
|
||||
connection.execute(
|
||||
text("INSERT INTO chats(id, title) VALUES (:id, 'Synthetic plan fixture')"),
|
||||
{"id": chat_id},
|
||||
)
|
||||
connection.execute(
|
||||
text("INSERT INTO chat_members(chat_id, user_id) VALUES (:chat_id, :user_id)"),
|
||||
{"chat_id": chat_id, "user_id": user_id},
|
||||
)
|
||||
connection.execute(
|
||||
text("""
|
||||
INSERT INTO messages(id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), :chat_id, :sender_id,
|
||||
'synthetic message ' || n::text,
|
||||
TIMESTAMPTZ '2025-01-01 00:00:00+00' + n * INTERVAL '1 microsecond'
|
||||
FROM generate_series(1, 10000) AS n
|
||||
"""),
|
||||
{"chat_id": chat_id, "sender_id": user_id},
|
||||
)
|
||||
connection.exec_driver_sql("ANALYZE messages")
|
||||
raw = connection.execute(
|
||||
text("""
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = :chat_id
|
||||
AND (created_at, id) > (TIMESTAMPTZ '2025-01-01 00:00:00+00',
|
||||
'00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 50
|
||||
"""),
|
||||
{"chat_id": chat_id},
|
||||
).scalar_one()
|
||||
plan_json = raw if isinstance(raw, list) else json.loads(raw)
|
||||
finally:
|
||||
transaction.rollback()
|
||||
|
||||
document = plan_json[0]
|
||||
|
||||
def contains_history_index(node: dict) -> bool:
|
||||
if node.get("Index Name") == "messages_history_idx":
|
||||
return True
|
||||
return any(contains_history_index(child) for child in node.get("Plans", []))
|
||||
|
||||
if not contains_history_index(document["Plan"]):
|
||||
raise SystemExit("Planner did not use messages_history_idx; inspect and revise the query/index.")
|
||||
print(json.dumps(document, indent=2, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
+527
@@ -0,0 +1,527 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from fastapi import FastAPI, Header, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from redis import Redis
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import and_, delete, func, or_, select, text, tuple_, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.exc import DBAPIError, OperationalError, TimeoutError as SQLAlchemyTimeoutError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .db import SessionLocal, engine
|
||||
from .errors import ApiError, error_response
|
||||
from .models import Chat, ChatMember, IdempotencyRecord, Message, User
|
||||
from .schemas import (
|
||||
ChatOut,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
MessageOut,
|
||||
MessagePage,
|
||||
SessionOut,
|
||||
UserOut,
|
||||
)
|
||||
from .settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger.api")
|
||||
password_hasher = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19_456,
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
type=Type.ID,
|
||||
)
|
||||
DUMMY_PASSWORD_HASH = password_hasher.hash("dummy-password-for-timing-only")
|
||||
redis_client = Redis.from_url(
|
||||
settings.cache_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
health_check_interval=30,
|
||||
)
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — Lab 3", version="1.3.0")
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{43}$")
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII)
|
||||
# Docker assigns each container a stable hostname equal to its container ID.
|
||||
# The load balancer forwards this value so tests can prove requests changed replicas.
|
||||
INSTANCE_ID = socket.gethostname()
|
||||
|
||||
|
||||
def _iso(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _user_out(user: User) -> dict:
|
||||
return {
|
||||
"id": str(user.id),
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"created_at": _iso(user.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _message_out(message: Message) -> dict:
|
||||
return {
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"created_at": _iso(message.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _chat_out(session, chat: Chat) -> dict:
|
||||
members = session.scalars(
|
||||
select(ChatMember.user_id)
|
||||
.where(ChatMember.chat_id == chat.id)
|
||||
.order_by(ChatMember.user_id)
|
||||
).all()
|
||||
return {
|
||||
"id": str(chat.id),
|
||||
"title": chat.title,
|
||||
"member_ids": [str(member_id) for member_id in members],
|
||||
"created_at": _iso(chat.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _api_error(code: str, message: str, status: int, challenge: str | None = None) -> ApiError:
|
||||
return ApiError(code, message, status, challenge)
|
||||
|
||||
|
||||
def _unauthorized(challenge: str = BEARER_CHALLENGE) -> ApiError:
|
||||
return _api_error("unauthorized", "Нет действительной идентификации", 401, challenge)
|
||||
|
||||
|
||||
def _encode_cursor(payload: dict) -> str:
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(value: str) -> dict:
|
||||
try:
|
||||
padded = value + ("=" * ((4 - len(value) % 4) % 4))
|
||||
raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("cursor must be an object")
|
||||
return payload
|
||||
except (ValueError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc:
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400) from exc
|
||||
|
||||
|
||||
def _cursor_position(payload: dict) -> tuple[datetime, uuid.UUID]:
|
||||
try:
|
||||
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time must include timezone")
|
||||
item_id = uuid.UUID(payload["i"])
|
||||
return created_at.astimezone(timezone.utc), item_id
|
||||
except (KeyError, TypeError, ValueError, AttributeError) as exc:
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400) from exc
|
||||
|
||||
|
||||
def _session_key(token: str) -> str:
|
||||
digest = hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
return "session:v1:" + digest
|
||||
|
||||
|
||||
def _parse_bearer(request: Request) -> str:
|
||||
header = request.headers.get("authorization", "")
|
||||
scheme, separator, token = header.partition(" ")
|
||||
if scheme.lower() != "bearer" or not separator or not TOKEN_RE.fullmatch(token):
|
||||
raise _unauthorized()
|
||||
return token
|
||||
|
||||
|
||||
def _load_session(token: str) -> dict:
|
||||
value = redis_client.get(_session_key(token))
|
||||
if value is None:
|
||||
raise _unauthorized()
|
||||
try:
|
||||
session = json.loads(value)
|
||||
user_id = uuid.UUID(session["user_id"])
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at.tzinfo is None or datetime.now(timezone.utc) >= expires_at:
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized()
|
||||
return {"user_id": user_id, "expires_at": expires_at}
|
||||
except ApiError:
|
||||
raise
|
||||
except (KeyError, TypeError, ValueError, AttributeError, json.JSONDecodeError):
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized() from None
|
||||
|
||||
|
||||
def _current_user(request: Request) -> tuple[User, str]:
|
||||
token = _parse_bearer(request)
|
||||
session_data = _load_session(token)
|
||||
with SessionLocal() as session:
|
||||
user = session.get(User, session_data["user_id"])
|
||||
if user is None:
|
||||
redis_client.delete(_session_key(token))
|
||||
raise _unauthorized()
|
||||
return user, token
|
||||
|
||||
|
||||
def _parse_basic(header: str) -> tuple[str, str]:
|
||||
scheme, separator, encoded = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not separator or not encoded:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (UnicodeError, ValueError, binascii.Error):
|
||||
raise _unauthorized(BASIC_CHALLENGE) from None
|
||||
if not USERNAME_RE.fullmatch(username) or not password:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
def _password_matches(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def _create_session(username: str, password: str) -> dict:
|
||||
with SessionLocal() as session:
|
||||
user = session.scalar(select(User).where(User.username == username))
|
||||
stored_hash = user.password_hash if user is not None else DUMMY_PASSWORD_HASH
|
||||
password_ok = _password_matches(stored_hash, password)
|
||||
if user is None or not password_ok:
|
||||
raise _unauthorized(BASIC_CHALLENGE)
|
||||
user_payload = _user_out(user)
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.session_ttl_seconds)
|
||||
for _ in range(3):
|
||||
token = secrets.token_urlsafe(32)
|
||||
stored_value = json.dumps(
|
||||
{"user_id": user_payload["id"], "expires_at": _iso(expires_at)},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
if redis_client.set(_session_key(token), stored_value, ex=settings.session_ttl_seconds, nx=True):
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": _iso(expires_at),
|
||||
"user": user_payload,
|
||||
}
|
||||
logger.error("session_token_collision_limit_reached")
|
||||
raise _api_error("unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
def _get_chat_for_member(session, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat | None:
|
||||
return session.scalar(
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_metadata_middleware(request: Request, call_next):
|
||||
request_id = str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception as exc:
|
||||
# Keep an unexpected failure bounded and ensure the API response still
|
||||
# identifies the request and the replica that created it.
|
||||
logger.error("internal_error request_id=%s type=%s", request_id, type(exc).__name__)
|
||||
response = error_response(request, "internal_error", "Внутренняя ошибка", 500)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.code, exc.message, exc.status, exc.challenge)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, _exc: RequestValidationError):
|
||||
return error_response(request, "invalid_request", "Неверный запрос", 400)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_error(request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code == 404:
|
||||
return error_response(request, "not_found", "Объект не найден", 404)
|
||||
return error_response(request, "invalid_request", "Неверный запрос", 400)
|
||||
|
||||
|
||||
@app.exception_handler(OperationalError)
|
||||
@app.exception_handler(SQLAlchemyTimeoutError)
|
||||
async def handle_database_unavailable(request: Request, exc: Exception):
|
||||
logger.warning("database_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
@app.exception_handler(RedisError)
|
||||
async def handle_cache_unavailable(request: Request, exc: RedisError):
|
||||
logger.warning("session_store_unavailable request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
|
||||
|
||||
@app.exception_handler(DBAPIError)
|
||||
async def handle_database_error(request: Request, exc: DBAPIError):
|
||||
if exc.connection_invalidated:
|
||||
logger.warning("database_connection_lost request_id=%s", request.state.request_id)
|
||||
return error_response(request, "unavailable", "Сервис временно недоступен", 503)
|
||||
logger.error("database_error request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "internal_error", "Внутренняя ошибка", 500)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected_error(request: Request, exc: Exception):
|
||||
logger.error("internal_error request_id=%s type=%s", request.state.request_id, type(exc).__name__)
|
||||
return error_response(request, "internal_error", "Внутренняя ошибка", 500)
|
||||
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health, responses={503: {"description": "Dependency unavailable"}})
|
||||
def ready():
|
||||
with SessionLocal() as session:
|
||||
session.execute(text("SELECT 1"))
|
||||
redis_client.ping()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", response_model=UserOut, status_code=201)
|
||||
def register_user(payload: CreateUser):
|
||||
password_hash = password_hasher.hash(payload.password)
|
||||
user = User(username=payload.username, display_name=payload.display_name, password_hash=password_hash)
|
||||
try:
|
||||
with SessionLocal.begin() as session:
|
||||
session.add(user)
|
||||
session.flush()
|
||||
except DBAPIError as exc:
|
||||
if getattr(getattr(exc, "orig", None), "sqlstate", None) == "23505":
|
||||
raise _api_error("conflict", "username занят", 409) from exc
|
||||
raise
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201)
|
||||
async def create_session(request: Request):
|
||||
if await request.body():
|
||||
raise _api_error("invalid_request", "Basic authentication must not include a body", 400)
|
||||
username, password = _parse_basic(request.headers.get("authorization", ""))
|
||||
return await run_in_threadpool(_create_session, username, password)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request):
|
||||
_user, token = _current_user(request)
|
||||
redis_client.delete(_session_key(token))
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserOut)
|
||||
def current_user(request: Request):
|
||||
user, _token = _current_user(request)
|
||||
return _user_out(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", response_model=ChatOut, status_code=201)
|
||||
def create_chat(payload: CreateChat, request: Request):
|
||||
user, _token = _current_user(request)
|
||||
member_ids = [uuid.UUID(value) for value in payload.member_ids]
|
||||
if user.id not in member_ids:
|
||||
raise _api_error("invalid_request", "Вызывающий должен входить в member_ids", 400)
|
||||
|
||||
try:
|
||||
with SessionLocal.begin() as session:
|
||||
chat = Chat(title=payload.title)
|
||||
session.add(chat)
|
||||
session.flush()
|
||||
session.add_all(ChatMember(chat_id=chat.id, user_id=member_id) for member_id in member_ids)
|
||||
session.flush()
|
||||
result = _chat_out(session, chat)
|
||||
except DBAPIError as exc:
|
||||
if getattr(getattr(exc, "orig", None), "sqlstate", None) in {"23503", "23505"}:
|
||||
raise _api_error("invalid_request", "Неизвестный участник", 400) from exc
|
||||
raise
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(request: Request, limit: int = 50, cursor: str | None = None):
|
||||
user, _token = _current_user(request)
|
||||
if limit < 1 or limit > 100:
|
||||
raise _api_error("invalid_request", "limit вне диапазона", 400)
|
||||
statement = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
)
|
||||
if cursor is not None:
|
||||
payload = _decode_cursor(cursor)
|
||||
if payload.get("u") != str(user.id):
|
||||
raise _api_error("invalid_request", "Неверный cursor", 400)
|
||||
created_at, chat_id = _cursor_position(payload)
|
||||
statement = statement.where(tuple_(Chat.created_at, Chat.id) > tuple_(created_at, chat_id))
|
||||
|
||||
with SessionLocal() as session:
|
||||
chats = session.scalars(statement.limit(limit + 1)).all()
|
||||
has_more = len(chats) > limit
|
||||
page = chats[:limit]
|
||||
items = [_chat_out(session, chat) for chat in page]
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor({"u": str(user.id), "t": _iso(last.created_at), "i": str(last.id)})
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatOut)
|
||||
def get_chat(chat_id: uuid.UUID, request: Request):
|
||||
user, _token = _current_user(request)
|
||||
with SessionLocal() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
return _chat_out(session, chat)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
|
||||
def create_message(
|
||||
chat_id: uuid.UUID,
|
||||
payload: CreateMessage,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
):
|
||||
user, _token = _current_user(request)
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
|
||||
raise _api_error("invalid_request", "Нужен корректный Idempotency-Key", 400)
|
||||
if not payload.text.strip():
|
||||
raise _api_error("invalid_request", "Сообщение не может состоять только из пробелов", 400)
|
||||
|
||||
# Hash the validated semantic JSON, not the raw bytes, so whitespace and
|
||||
# object key order do not change the identity of a request.
|
||||
canonical_body = json.dumps(
|
||||
payload.model_dump(mode="json"), ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
||||
)
|
||||
body_hash = hashlib.sha256(canonical_body.encode("utf-8")).hexdigest()
|
||||
path = request.url.path
|
||||
now = datetime.now(timezone.utc)
|
||||
expires_at = now + timedelta(hours=24)
|
||||
scope = (
|
||||
IdempotencyRecord.user_id == user.id,
|
||||
IdempotencyRecord.method == "POST",
|
||||
IdempotencyRecord.path == path,
|
||||
IdempotencyRecord.idempotency_key == idempotency_key,
|
||||
)
|
||||
|
||||
with SessionLocal.begin() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
|
||||
# A key becomes reusable only after its 24-hour retention window.
|
||||
session.execute(delete(IdempotencyRecord).where(*scope, IdempotencyRecord.expires_at <= now))
|
||||
insert_record = (
|
||||
pg_insert(IdempotencyRecord)
|
||||
.values(
|
||||
user_id=user.id,
|
||||
method="POST",
|
||||
path=path,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=body_hash,
|
||||
response_body={},
|
||||
expires_at=expires_at,
|
||||
)
|
||||
.on_conflict_do_nothing(constraint="idempotency_records_scope_key_uq")
|
||||
.returning(IdempotencyRecord.id)
|
||||
)
|
||||
record_id = session.execute(insert_record).scalar_one_or_none()
|
||||
|
||||
if record_id is None:
|
||||
# A concurrent insert waits on the unique constraint. At READ
|
||||
# COMMITTED the winning transaction is visible to this SELECT.
|
||||
existing = session.scalar(select(IdempotencyRecord).where(*scope))
|
||||
if existing is None:
|
||||
raise _api_error("unavailable", "Сервис временно недоступен", 503)
|
||||
if existing.request_hash != body_hash:
|
||||
raise _api_error("conflict", "Idempotency-Key уже использован для другого запроса", 409)
|
||||
result = existing.response_body
|
||||
else:
|
||||
message = Message(chat_id=chat_id, sender_id=user.id, text=payload.text)
|
||||
session.add(message)
|
||||
session.flush()
|
||||
result = _message_out(message)
|
||||
session.execute(
|
||||
update(IdempotencyRecord)
|
||||
.where(IdempotencyRecord.id == record_id)
|
||||
.values(response_body=result)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(chat_id: uuid.UUID, request: Request, limit: int = 50, cursor: str | None = None):
|
||||
user, _token = _current_user(request)
|
||||
with SessionLocal() as session:
|
||||
chat = _get_chat_for_member(session, chat_id, user.id)
|
||||
if chat is None:
|
||||
raise _api_error("not_found", "Объект не найден", 404)
|
||||
if limit < 1 or limit > 100:
|
||||
raise _api_error("invalid_request", "limit вне диапазона", 400)
|
||||
after = None
|
||||
if cursor is not None:
|
||||
payload = _decode_cursor(cursor)
|
||||
if payload.get("c") != str(chat_id):
|
||||
raise _api_error("invalid_request", "cursor от другого чата", 400)
|
||||
after = _cursor_position(payload)
|
||||
statement = select(Message).where(Message.chat_id == chat_id)
|
||||
if after is not None:
|
||||
statement = statement.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
||||
statement = statement.order_by(Message.created_at, Message.id).limit(limit + 1)
|
||||
rows = session.scalars(statement).all()
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
items = [_message_out(message) for message in page]
|
||||
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor({"c": str(chat_id), "t": _iso(last.created_at), "i": str(last.id)})
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,36 @@
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from .db import engine
|
||||
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parents[2] / "migrations"
|
||||
|
||||
|
||||
def migrate() -> None:
|
||||
with engine.begin() as connection:
|
||||
connection.exec_driver_sql("SELECT pg_advisory_xact_lock(2026102202)")
|
||||
connection.exec_driver_sql(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations "
|
||||
"(version VARCHAR(128) PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)"
|
||||
)
|
||||
applied = set(connection.execute(text("SELECT version FROM schema_migrations")).scalars())
|
||||
for path in sorted(MIGRATIONS.glob("*.sql")):
|
||||
version = path.stem
|
||||
if version in applied:
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
for statement in sql.split(";"):
|
||||
if statement.strip():
|
||||
connection.exec_driver_sql(statement)
|
||||
connection.execute(
|
||||
text("INSERT INTO schema_migrations(version) VALUES (:version)"),
|
||||
{"version": version},
|
||||
)
|
||||
print(f"Applied migration {version}")
|
||||
engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate()
|
||||
@@ -0,0 +1,86 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, ForeignKeyConstraint, Index, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
username: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
title: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
__table_args__ = (
|
||||
Index("chat_members_user_id_idx", "user_id", "chat_id"),
|
||||
)
|
||||
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="RESTRICT"), primary_key=True
|
||||
)
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
__table_args__ = (
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
name="messages_sender_is_chat_member_fk",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
Index("messages_history_idx", "chat_id", "created_at", "id"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
text: Mapped[str] = mapped_column(String(4000), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
|
||||
class IdempotencyRecord(Base):
|
||||
"""Shared, transactional result cache for retried message POST requests."""
|
||||
|
||||
__tablename__ = "idempotency_records"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"user_id", "method", "path", "idempotency_key",
|
||||
name="idempotency_records_scope_key_uq",
|
||||
),
|
||||
Index("idempotency_records_expires_at_idx", "expires_at"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
method: Mapped[str] = mapped_column(String(8), nullable=False)
|
||||
path: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
request_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
response_body: Mapped[dict] = mapped_column(JSONB, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
@@ -0,0 +1,94 @@
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: StrictStr = Field(min_length=3, max_length=32, pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: StrictStr = Field(min_length=1, max_length=100)
|
||||
password: StrictStr = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("display_name must contain a non-whitespace character")
|
||||
return value
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: StrictStr = Field(min_length=1, max_length=100)
|
||||
member_ids: list[StrictStr] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must contain a non-whitespace character")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def members_are_unique_uuids(cls, values: list[str]) -> list[str]:
|
||||
import uuid
|
||||
|
||||
try:
|
||||
normalized = [str(uuid.UUID(value)) for value in values]
|
||||
except (ValueError, AttributeError, TypeError) as exc:
|
||||
raise ValueError("member_ids must contain UUIDs") from exc
|
||||
if len(normalized) != len(set(normalized)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return normalized
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: list[ChatOut]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: StrictStr = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class MessageOut(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: list[MessageOut]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
error: dict[str, str]
|
||||
@@ -0,0 +1,37 @@
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _secret(file_variable: str, value_variable: str) -> str:
|
||||
file_path = os.environ.get(file_variable)
|
||||
if file_path:
|
||||
value = Path(file_path).read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
value = os.environ.get(value_variable, "").strip()
|
||||
if not value:
|
||||
raise RuntimeError(f"Required setting {file_variable} is missing")
|
||||
return value
|
||||
|
||||
|
||||
def load_database_url() -> str:
|
||||
return _secret("DATABASE_URL_FILE", "DATABASE_URL")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
cache_url: str
|
||||
session_ttl_seconds: int
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
try:
|
||||
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
except ValueError as exc:
|
||||
raise RuntimeError("SESSION_TTL_SECONDS must be an integer") from exc
|
||||
if ttl < 1 or ttl > 31_536_000:
|
||||
raise RuntimeError("SESSION_TTL_SECONDS must be between 1 and 31536000")
|
||||
return Settings(
|
||||
cache_url=_secret("CACHE_URL_FILE", "CACHE_URL"),
|
||||
session_ttl_seconds=ttl,
|
||||
)
|
||||
Reference in New Issue
Block a user