Implement lab4 S3 attachments and reliability checks

This commit is contained in:
Polusikkkk
2026-11-05 18:42:22 +03:00
parent ec540a1a72
commit 0f6615dbb9
51 changed files with 6018 additions and 23 deletions
View File
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import base64
import binascii
import hashlib
import re
import secrets
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerificationError
from starlette.concurrency import run_in_threadpool
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}", re.ASCII)
password_hasher = PasswordHasher(
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
salt_len=16,
type=Type.ID,
)
DUMMY_PASSWORD_HASH = password_hasher.hash(
secrets.token_urlsafe(32)
)
async def hash_password(password: str) -> str:
return await run_in_threadpool(
password_hasher.hash,
password,
)
async def verify_password(
password_hash: str,
password: str,
) -> bool:
try:
return await run_in_threadpool(
password_hasher.verify,
password_hash,
password,
)
except VerificationError:
return False
def parse_basic_credentials(
authorization: str | None,
) -> tuple[str, str] | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "basic":
return None
try:
decoded = base64.b64decode(
parts[1],
validate=True,
).decode("utf-8")
except (binascii.Error, UnicodeError, ValueError):
return None
username, separator, password = decoded.partition(":")
if not separator:
return None
if USERNAME_RE.fullmatch(username) is None:
return None
if not 12 <= len(password) <= 128:
return None
return username, password
def parse_bearer_token(
authorization: str | None,
) -> str | None:
if authorization is None or len(authorization) > 2048:
return None
parts = authorization.split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return None
token = parts[1]
if re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
return None
return token
def generate_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
+129
View File
@@ -0,0 +1,129 @@
from __future__ import annotations
import json
import logging
import os
from datetime import datetime, timezone
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from app.store import store
logger = logging.getLogger("messenger.cache")
CACHE_TTL_SECONDS = int(
os.getenv("USER_CACHE_TTL_SECONDS", "60")
)
if not 1 <= CACHE_TTL_SECONDS <= 3600:
raise ValueError(
"USER_CACHE_TTL_SECONDS must be between 1 and 3600"
)
redis_client = Redis(
host=os.getenv("REDIS_HOST", "redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
decode_responses=True,
socket_connect_timeout=0.2,
socket_timeout=0.2,
retry_on_timeout=False,
max_connections=10,
)
def serialize_user(user: dict) -> str:
created_at = user["created_at"]
return json.dumps(
{
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": created_at.astimezone(
timezone.utc
).isoformat().replace("+00:00", "Z"),
},
ensure_ascii=False,
separators=(",", ":"),
)
def deserialize_user(
raw: str,
expected_id: UUID,
) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("Invalid cached user")
expected_fields = {
"id",
"username",
"display_name",
"created_at",
}
if set(data) != expected_fields:
raise ValueError("Invalid cached user fields")
if not all(isinstance(value, str) for value in data.values()):
raise ValueError("Invalid cached user types")
user_id = UUID(data["id"])
if user_id != expected_id:
raise ValueError("Cached user ID mismatch")
created_at = datetime.fromisoformat(
data["created_at"].replace("Z", "+00:00")
)
if created_at.tzinfo is None:
raise ValueError("Cached timestamp has no timezone")
return {
"id": user_id,
"username": data["username"],
"display_name": data["display_name"],
"created_at": created_at,
}
async def get_cached_user(user_id: UUID) -> dict | None:
key = f"user:v1:{user_id}"
try:
raw = await redis_client.get(key)
if raw is not None:
return deserialize_user(raw, user_id)
except RedisError:
logger.warning("User cache read unavailable")
except (ValueError, TypeError, OverflowError):
logger.warning("Invalid user cache entry ignored")
user = await store.get_user(user_id)
if user is None:
return None
try:
await redis_client.set(
key,
serialize_user(user),
ex=CACHE_TTL_SECONDS,
)
except RedisError:
logger.warning("User cache write unavailable")
return user
async def close_cache() -> None:
await redis_client.aclose()
+208
View File
@@ -0,0 +1,208 @@
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime, timedelta, timezone
import json
import os
import sys
import time
from uuid import UUID
import psycopg
from psycopg.rows import dict_row
from botocore.exceptions import ClientError
from app.object_locks import object_lock_id
from app.storage import bucket_name, get_client
def managed_key(key: str) -> bool:
prefix = "originals/"
if not key.startswith(prefix):
return False
suffix = key[len(prefix):]
try:
return str(UUID(suffix)) == suffix
except ValueError:
return False
def database_connection():
return psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=3,
options=(
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
autocommit=True,
row_factory=dict_row,
)
def sweep(*, apply: bool, grace_seconds: int) -> dict:
cutoff = datetime.now(timezone.utc) - timedelta(
seconds=grace_seconds
)
counts = Counter({
"scanned": 0,
"kept": 0,
"fresh": 0,
"busy": 0,
"ignored": 0,
"gone": 0,
"candidates": 0,
"deleted": 0,
})
with database_connection() as conn:
client = get_client()
bucket = bucket_name()
pages = client.get_paginator("list_objects_v2")
for page in pages.paginate(
Bucket=bucket,
Prefix="originals/",
PaginationConfig={"PageSize": 200},
):
for item in page.get("Contents", []):
counts["scanned"] += 1
key = item["Key"]
if not managed_key(key):
counts["ignored"] += 1
continue
if item["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
with conn.transaction():
conn.execute(
"SET LOCAL "
"idle_in_transaction_session_timeout = '60s'"
)
locked = conn.execute(
"SELECT pg_try_advisory_xact_lock(%s) AS locked",
(object_lock_id(bucket, key),),
).fetchone()["locked"]
if not locked:
counts["busy"] += 1
continue
metadata = conn.execute(
"""
SELECT 1
FROM attachments
WHERE object_key = %s
""",
(key,),
).fetchone()
if metadata is not None:
counts["kept"] += 1
continue
try:
current = client.head_object(
Bucket=bucket,
Key=key,
)
except ClientError as exc:
status = exc.response.get(
"ResponseMetadata", {}
).get("HTTPStatusCode")
if status == 404:
counts["gone"] += 1
continue
raise
if current["LastModified"] >= cutoff:
counts["fresh"] += 1
continue
counts["candidates"] += 1
print(
json.dumps({
"action": "delete" if apply else "would_delete",
"key": key,
}),
flush=True,
)
if apply:
client.delete_object(
Bucket=bucket,
Key=key,
)
counts["deleted"] += 1
return {
"mode": "apply" if apply else "dry-run",
"grace_seconds": grace_seconds,
**dict(counts),
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true")
parser.add_argument("--grace-seconds", type=int, default=86400)
parser.add_argument("--allow-short-grace", action="store_true")
parser.add_argument("--interval-seconds", type=int, default=0)
args = parser.parse_args()
if args.grace_seconds < 60:
parser.error("grace must be at least 60 seconds")
if args.grace_seconds < 3600 and not args.allow_short_grace:
parser.error(
"short test grace requires --allow-short-grace"
)
if args.interval_seconds != 0 and args.interval_seconds < 60:
parser.error("interval must be zero or at least 60 seconds")
if args.grace_seconds < 3600:
print(
"WARNING: short grace is for controlled local tests",
file=sys.stderr,
flush=True,
)
while True:
try:
result = sweep(
apply=args.apply,
grace_seconds=args.grace_seconds,
)
except Exception as exc:
print(
json.dumps({
"status": "failed",
"error_type": type(exc).__name__,
}),
file=sys.stderr,
flush=True,
)
return 1
print(json.dumps(result, sort_keys=True), flush=True)
if args.interval_seconds == 0:
return 0
time.sleep(args.interval_seconds)
if __name__ == "__main__":
raise SystemExit(main())
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
import os
SESSION_TTL_SECONDS = int(
os.getenv("SESSION_TTL_SECONDS", "3600")
)
if SESSION_TTL_SECONDS < 1:
raise ValueError("SESSION_TTL_SECONDS must be positive")
+44
View File
@@ -0,0 +1,44 @@
from __future__ import annotations
import os
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
pool = AsyncConnectionPool(
conninfo="",
kwargs={
"host": os.getenv("PGHOST", "postgres"),
"port": int(os.getenv("PGPORT", "5432")),
"dbname": os.getenv("PGDATABASE", "messenger"),
"user": os.getenv("PGUSER", "messenger"),
"password": os.environ.get("PGPASSWORD", ""),
"connect_timeout": 3,
"options": (
"-c statement_timeout=3000 "
"-c lock_timeout=2000 "
"-c idle_in_transaction_session_timeout=10000"
),
"row_factory": dict_row,
},
min_size=1,
max_size=5,
timeout=3,
max_waiting=20,
open=False,
check=AsyncConnectionPool.check_connection,
)
async def open_db() -> None:
await pool.open(wait=True, timeout=10)
async def close_db() -> None:
await pool.close()
async def check_db() -> None:
async with pool.connection() as conn:
await conn.execute("SELECT 1")
+48
View File
@@ -0,0 +1,48 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.auth import hash_token, parse_bearer_token
from app.cache import get_cached_user
from app.errors import not_found, unauthorized
from app.store import store
from app.validation import parse_uuid
async def current_user(request: Request) -> tuple[dict, str]:
token = parse_bearer_token(
request.headers.get("authorization")
)
if token is None:
raise unauthorized()
token_digest = hash_token(token)
user_id = await store.get_session_user_id(token_digest)
if user_id is None:
raise unauthorized()
user = await get_cached_user(user_id)
if user is None:
raise unauthorized()
return user, token_digest
async def accessible_chat(
raw_chat_id: str,
user_id: UUID,
) -> tuple[UUID, dict]:
chat_id = parse_uuid(raw_chat_id)
chat = await store.get_accessible_chat(chat_id, user_id)
if chat is None:
raise not_found()
return chat_id, chat
+71
View File
@@ -0,0 +1,71 @@
from __future__ import annotations
from uuid import uuid4
from fastapi import Request
from fastapi.responses import JSONResponse
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
challenge: str | None = None,
):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.challenge = challenge
def invalid(message: str = "Некорректный запрос") -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(scheme: str = "Bearer") -> ApiError:
if scheme == "Basic":
challenge = 'Basic realm="messenger", charset="UTF-8"'
else:
challenge = 'Bearer realm="messenger"'
return ApiError(
401,
"unauthorized",
"Недействительная аутентификация",
challenge,
)
def not_found() -> ApiError:
return ApiError(404, "not_found", "Объект не найден")
def error_response(
request: Request,
error: ApiError,
) -> JSONResponse:
request_id = getattr(
request.state,
"request_id",
str(uuid4()),
)
headers = {"X-Request-Id": request_id}
if error.challenge is not None:
headers["WWW-Authenticate"] = error.challenge
return JSONResponse(
status_code=error.status,
content={
"error": {
"code": error.code,
"message": error.message,
"request_id": request_id,
}
},
headers=headers,
)
+174
View File
@@ -0,0 +1,174 @@
from __future__ import annotations
import hashlib
import json
from uuid import UUID, uuid4
from app.db import pool
from app.errors import ApiError, invalid, not_found
async def create_message_once(
chat_id: UUID,
sender_id: UUID,
text: str,
key: str,
attachment_ids: list[UUID] | None = None,
) -> dict:
attachment_ids = list(
attachment_ids if attachment_ids is not None else []
)
if (
len(attachment_ids) > 10
or len(set(attachment_ids)) != len(attachment_ids)
):
raise invalid("Некорректный список вложений")
if not isinstance(text, str) or len(text) > 4000:
raise invalid("Некорректный текст сообщения")
if not text.strip() and not attachment_ids:
raise invalid("Сообщение должно содержать текст или вложение")
scope = json.dumps(
[
str(sender_id),
"POST",
f"/api/v1/chats/{chat_id}/messages",
key,
],
separators=(",", ":"),
)
lock_id = int.from_bytes(
hashlib.sha256(scope.encode("utf-8")).digest()[:8],
byteorder="big",
signed=True,
)
async with pool.connection() as conn:
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(lock_id,),
)
cursor = await conn.execute(
"""
SELECT i.request_text,
i.request_attachment_ids,
m.id, m.chat_id, m.sender_id,
m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments AS ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = %s
AND i.chat_id = %s
AND i.http_method = 'POST'
AND i.idempotency_key = %s
""",
(sender_id, chat_id, key),
)
previous = await cursor.fetchone()
if previous is not None:
if (
previous["request_text"] != text
or previous["request_attachment_ids"] != attachment_ids
):
raise ApiError(
409,
"conflict",
"Ключ уже использован с другим сообщением",
)
message = {
field: previous[field]
for field in (
"id",
"chat_id",
"sender_id",
"text",
"created_at",
"attachment_ids",
)
}
else:
if attachment_ids:
cursor = await conn.execute(
"""
SELECT id
FROM attachments
WHERE id = ANY(%s::uuid[])
AND chat_id = %s
AND status = 'ready'
ORDER BY id
FOR SHARE
""",
(attachment_ids, chat_id),
)
available = await cursor.fetchall()
if len(available) != len(attachment_ids):
raise not_found()
cursor = await conn.execute(
"""
INSERT INTO messages (
id, chat_id, sender_id, text
)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id,
text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
if attachment_ids:
async with conn.cursor() as cursor:
await cursor.executemany(
"""
INSERT INTO message_attachments (
message_id, attachment_id, position
)
VALUES (%s, %s, %s)
""",
[
(message["id"], attachment_id, position)
for position, attachment_id
in enumerate(attachment_ids)
],
)
await conn.execute(
"""
INSERT INTO message_idempotency (
user_id,
chat_id,
http_method,
idempotency_key,
request_text,
request_attachment_ids,
message_id
)
VALUES (%s, %s, 'POST', %s, %s, %s::uuid[], %s)
""",
(
sender_id,
chat_id,
key,
text,
attachment_ids,
message["id"],
),
)
message["attachment_ids"] = attachment_ids
return message
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import io
import unicodedata
from PIL import Image, UnidentifiedImageError
from app.errors import ApiError, invalid
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
FORMAT_TO_MIME = {
"PNG": "image/png",
"JPEG": "image/jpeg",
}
def validate_filename(value: str | None) -> str:
if (
value is None
or not 1 <= len(value) <= 255
or not value.strip()
):
raise invalid("Некорректное имя файла")
for char in value:
if char in "/\\" or unicodedata.category(char) == "Cc":
raise invalid("Некорректное имя файла")
return value
def inspect_image(data: bytes, declared_type: str) -> str:
if len(data) > MAX_BYTES:
raise ApiError(
413,
"payload_too_large",
"Файл превышает 10 MiB",
)
if declared_type not in FORMAT_TO_MIME.values():
raise ApiError(
415,
"unsupported_media_type",
"Допустимы только image/png и image/jpeg",
)
try:
with Image.open(io.BytesIO(data)) as image:
detected = FORMAT_TO_MIME.get(image.format or "")
width, height = image.size
pixels = width * height
except Image.DecompressionBombError:
raise ApiError(
413,
"payload_too_large",
"Слишком много пикселей",
) from None
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
raise ApiError(
415,
"unsupported_media_type",
"Файл не является корректным PNG/JPEG",
) from None
if detected is None or detected != declared_type:
raise ApiError(
415,
"unsupported_media_type",
"Содержимое не соответствует Content-Type",
)
if width < 1 or height < 1 or pixels > MAX_PIXELS:
raise ApiError(
413,
"payload_too_large",
"Слишком много пикселей",
)
try:
with Image.open(io.BytesIO(data)) as image:
image.verify()
with Image.open(io.BytesIO(data)) as image:
image.load()
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError):
raise ApiError(
415,
"unsupported_media_type",
"Файл повреждён",
) from None
return detected
+7
View File
@@ -0,0 +1,7 @@
from __future__ import annotations
import socket
from uuid import uuid4
INSTANCE_ID = f"{socket.gethostname()}:{uuid4().hex[:12]}"
+116
View File
@@ -0,0 +1,116 @@
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from psycopg import InterfaceError, OperationalError
from psycopg.errors import LockNotAvailable, QueryCanceled
from psycopg_pool import PoolTimeout, TooManyRequests
from starlette.exceptions import HTTPException
from app.cache import close_cache
from app.instance import INSTANCE_ID
from app.db import close_db, open_db
from app.errors import ApiError, error_response, invalid, not_found
from app.routers import attachments, chats, health, messages, sessions, users
logger = logging.getLogger("messenger.api")
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
await open_db()
yield
finally:
await close_cache()
await close_db()
app = FastAPI(
title="Replicated PostgreSQL messenger — Lab 3",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
response = await call_next(request)
except ApiError as exc:
response = error_response(request, exc)
except (
OperationalError,
InterfaceError,
PoolTimeout,
TooManyRequests,
QueryCanceled,
LockNotAvailable,
) as exc:
logger.warning(
"Database unavailable request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
503,
"unavailable",
"Сервис временно недоступен",
),
)
except Exception as exc:
logger.error(
"Unhandled error request_id=%s error_type=%s",
request.state.request_id,
type(exc).__name__,
)
response = error_response(
request,
ApiError(
500,
"internal_error",
"Внутренняя ошибка сервера",
),
)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc):
return error_response(request, invalid())
@app.exception_handler(HTTPException)
async def http_error_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
error = not_found()
else:
error = invalid("Недопустимый HTTP-запрос")
return error_response(request, error)
app.include_router(health.router)
app.include_router(users.router)
app.include_router(sessions.router)
app.include_router(chats.router)
app.include_router(messages.router)
app.include_router(attachments.router)
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import hashlib
import os
from pathlib import Path
import psycopg
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
MIGRATION_LOCK_ID = 202602001
def apply_migrations() -> None:
files = sorted(MIGRATIONS_DIR.glob("[0-9]*_*.sql"))
if not files:
raise RuntimeError("Migration files not found")
with psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=5,
options="-c statement_timeout=30000 -c lock_timeout=10000",
) as conn:
conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(MIGRATION_LOCK_ID,),
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL
DEFAULT clock_timestamp()
)
"""
)
for path in files:
version = path.name
content = path.read_bytes()
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute(
"""
SELECT checksum
FROM schema_migrations
WHERE version = %s
""",
(version,),
).fetchone()
if row is not None:
if row[0] != checksum:
raise RuntimeError(
f"Applied migration was modified: {version}"
)
print(f"Already applied: {version}", flush=True)
continue
conn.execute(content.decode("utf-8"), prepare=False)
conn.execute(
"""
INSERT INTO schema_migrations (version, checksum)
VALUES (%s, %s)
""",
(version, checksum),
)
print(f"Executed: {version} (pending commit)", flush=True)
print("Migrations committed successfully", flush=True)
if __name__ == "__main__":
apply_migrations()
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
import hashlib
def object_lock_id(bucket: str, object_key: str) -> int:
value = f"s3-object\0{bucket}\0{object_key}".encode("utf-8")
return int.from_bytes(
hashlib.sha256(value).digest()[:8],
byteorder="big",
signed=True,
)
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
import base64
import binascii
import json
import re
from datetime import datetime
from uuid import UUID
from fastapi import Request
from fastapi.responses import JSONResponse
from app.errors import invalid
from app.responses import json_response, utc_text
def encode_cursor(scope: str, item: dict) -> str:
raw = json.dumps(
{
"scope": scope,
"created_at": utc_text(item["created_at"]),
"id": str(item["id"]),
},
separators=(",", ":"),
).encode("utf-8")
return (
base64.urlsafe_b64encode(raw)
.decode("ascii")
.rstrip("=")
)
def decode_cursor(
cursor: str,
scope: str,
) -> tuple[datetime, UUID]:
if not cursor or len(cursor) > 2048:
raise invalid("Некорректный cursor")
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.b64decode(
padded,
altchars=b"-_",
validate=True,
)
data = json.loads(raw.decode("utf-8"))
if (
not isinstance(data, dict)
or set(data) != {"scope", "created_at", "id"}
or data["scope"] != scope
):
raise ValueError
timestamp = data["created_at"]
if (
not isinstance(timestamp, str)
or not timestamp.endswith("Z")
or not isinstance(data["id"], str)
):
raise ValueError
created_at = datetime.fromisoformat(
timestamp[:-1] + "+00:00"
)
item_id = UUID(data["id"])
return created_at, item_id
except (
ValueError,
TypeError,
UnicodeError,
binascii.Error,
OverflowError,
):
raise invalid("Некорректный cursor") from None
def pagination(
request: Request,
scope: str,
) -> tuple[int, tuple[datetime, UUID] | None]:
raw_limit = request.query_params.get("limit", "50")
if (
len(raw_limit) > 10
or re.fullmatch(r"[0-9]+", raw_limit) is None
):
raise invalid("Некорректный limit")
limit = int(raw_limit)
if not 1 <= limit <= 100:
raise invalid("Некорректный limit")
raw_cursor = request.query_params.get("cursor")
after = None
if raw_cursor is not None:
after = decode_cursor(raw_cursor, scope)
return limit, after
def page_response(
rows: list[dict],
limit: int,
scope: str,
) -> JSONResponse:
items = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor(scope, items[-1])
return json_response(
{
"items": items,
"next_cursor": next_cursor,
}
)
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID
from fastapi.responses import JSONResponse
def utc_text(value: datetime) -> str:
return (
value.astimezone(timezone.utc)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
def to_json(value):
if isinstance(value, UUID):
return str(value)
if isinstance(value, datetime):
return utc_text(value)
if isinstance(value, dict):
return {
key: to_json(item)
for key, item in value.items()
}
if isinstance(value, (list, tuple)):
return [to_json(item) for item in value]
return value
def json_response(value, status: int = 200) -> JSONResponse:
return JSONResponse(
status_code=status,
content=to_json(value),
)
View File
+272
View File
@@ -0,0 +1,272 @@
from __future__ import annotations
import asyncio
import hashlib
from contextlib import asynccontextmanager
from uuid import UUID, uuid4
from fastapi import APIRouter, Request
from fastapi.responses import Response
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from app.db import pool
from app.dependencies import accessible_chat, current_user
from app.errors import ApiError, invalid, not_found
from app.images import MAX_BYTES, inspect_image, validate_filename
from app.object_locks import object_lock_id
from app.responses import json_response
from app.storage import bucket_name, get_object, put_object
from app.validation import parse_uuid
router = APIRouter()
binary_slot = asyncio.Semaphore(1)
PUBLIC_FIELDS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"created_at",
"updated_at",
)
@asynccontextmanager
async def binary_operation():
try:
await asyncio.wait_for(binary_slot.acquire(), timeout=3)
except TimeoutError:
raise ApiError(
503,
"unavailable",
"Обработка файлов временно занята",
) from None
try:
yield
finally:
binary_slot.release()
def public_attachment(row: dict) -> dict:
result = {field: row[field] for field in PUBLIC_FIELDS}
result["variants"] = []
result["error_code"] = None
return result
async def read_image_body(request: Request) -> bytes:
lengths = request.headers.getlist("content-length")
if len(lengths) > 1:
raise invalid("Некорректный Content-Length")
expected = None
if lengths:
value = lengths[0]
if not value.isascii() or not value.isdecimal():
raise invalid("Некорректный Content-Length")
if len(value) > 20:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
expected = int(value)
if expected > MAX_BYTES:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
data = bytearray()
async for chunk in request.stream():
if len(data) + len(chunk) > MAX_BYTES:
raise ApiError(
413, "payload_too_large", "Файл превышает 10 MiB"
)
data.extend(chunk)
if expected is not None and len(data) != expected:
raise invalid("Размер тела не соответствует Content-Length")
return bytes(data)
async def accessible_attachment(
attachment_id: UUID,
user_id: UUID,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT a.id, a.chat_id, a.owner_id,
a.filename, a.content_type, a.size_bytes,
a.sha256, a.object_key, a.status,
a.created_at, a.updated_at
FROM attachments AS a
WHERE a.id = %s
AND EXISTS (
SELECT 1
FROM chat_members AS cm
WHERE cm.chat_id = a.chat_id
AND cm.user_id = %s
)
""",
(attachment_id, user_id),
)
row = await cursor.fetchone()
if row is None:
raise not_found()
return row
@router.post("/api/v1/chats/{chat_id}/attachments")
async def upload_attachment(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(chat_id, user["id"])
filenames = request.query_params.getlist("filename")
if len(filenames) != 1:
raise invalid("Требуется одно имя файла")
filename = validate_filename(filenames[0])
content_types = request.headers.getlist("content-type")
if len(content_types) != 1:
raise ApiError(
415,
"unsupported_media_type",
"Требуется Content-Type изображения",
)
declared_type = content_types[0].split(";", 1)[0].strip().lower()
if declared_type not in ("image/png", "image/jpeg"):
raise ApiError(
415,
"unsupported_media_type",
"Допустимы только image/png и image/jpeg",
)
async with binary_operation():
try:
data = await asyncio.wait_for(
read_image_body(request),
timeout=60,
)
except ClientDisconnect:
raise invalid("Загрузка файла прервана") from None
except TimeoutError:
raise invalid("Превышено время загрузки файла") from None
content_type = await run_in_threadpool(
inspect_image,
data,
declared_type,
)
attachment_id = uuid4()
object_key = f"originals/{attachment_id}"
digest = hashlib.sha256(data).hexdigest()
async with pool.connection() as conn:
await conn.execute(
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
)
await conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(object_lock_id(bucket_name(), object_key),),
)
await put_object(object_key, data, content_type)
cursor = await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename,
content_type, size_bytes, sha256, object_key
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id, chat_id, owner_id, filename,
content_type, size_bytes, sha256,
status, created_at, updated_at
""",
(
attachment_id,
chat_uuid,
user["id"],
filename,
content_type,
len(data),
digest,
object_key,
),
)
row = await cursor.fetchone()
return json_response(public_attachment(row), 201)
@router.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: str, request: Request):
user, _ = await current_user(request)
row = await accessible_attachment(
parse_uuid(attachment_id),
user["id"],
)
return json_response(public_attachment(row))
@router.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(attachment_id: str, request: Request):
user, _ = await current_user(request)
row = await accessible_attachment(
parse_uuid(attachment_id),
user["id"],
)
variants = request.query_params.getlist("variant")
if len(variants) > 1:
raise invalid("Допускается один вариант изображения")
if variants and variants[0] != "original":
raise not_found()
if row["status"] != "ready":
raise ApiError(
409,
"conflict",
"Вложение ещё не готово",
)
async with binary_operation():
data = await get_object(row["object_key"])
if (
len(data) != row["size_bytes"]
or hashlib.sha256(data).hexdigest() != row["sha256"]
):
raise ApiError(
503,
"unavailable",
"Оригинал временно недоступен",
)
return Response(
content=data,
media_type=row["content_type"],
headers={
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
},
)
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import InvalidMembersError, store
from app.validation import parse_uuid, read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/chats")
async def create_chat(request: Request):
user, _ = await current_user(request)
payload = await read_payload(
request,
{"title", "member_ids"},
)
if not valid_text(payload["title"], 100):
raise invalid("Некорректный title")
raw_members = payload["member_ids"]
if (
not isinstance(raw_members, list)
or not 1 <= len(raw_members) <= 100
):
raise invalid("Некорректный member_ids")
member_ids = [parse_uuid(item) for item in raw_members]
if len(set(member_ids)) != len(member_ids):
raise invalid("В member_ids есть дубликаты")
if user["id"] not in member_ids:
raise invalid("Создатель должен входить в member_ids")
try:
chat = await store.create_chat(
payload["title"],
member_ids,
)
except InvalidMembersError:
raise invalid(
"В member_ids есть неизвестный пользователь"
) from None
return json_response(chat, 201)
@router.get("/api/v1/chats")
async def list_chats(request: Request):
user, _ = await current_user(request)
scope = f"chats:{user['id']}"
limit, after = pagination(request, scope)
rows = await store.list_chats(user["id"], limit, after)
return page_response(rows, limit, scope)
@router.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
user, _ = await current_user(request)
_, chat = await accessible_chat(chat_id, user["id"])
return json_response(chat)
+20
View File
@@ -0,0 +1,20 @@
from __future__ import annotations
from fastapi import APIRouter
from app.db import check_db
from app.storage import check_storage
router = APIRouter()
@router.get("/health/live")
async def health_live():
return {"status": "ok"}
@router.get("/health/ready")
async def health_ready():
await check_db()
await check_storage()
return {"status": "ok"}
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import re
from fastapi import APIRouter, Request
from app.dependencies import accessible_chat, current_user
from app.errors import invalid
from app.idempotency import create_message_once
from app.pagination import page_response, pagination
from app.responses import json_response
from app.store import store
from app.validation import parse_uuid, read_payload
router = APIRouter()
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
@router.post("/api/v1/chats/{chat_id}/messages")
async def create_message(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
keys = request.headers.getlist("idempotency-key")
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
raise invalid("Требуется корректный Idempotency-Key")
payload = await read_payload(
request,
{"text"},
optional_fields={"attachment_ids"},
)
text = payload["text"]
if not isinstance(text, str) or len(text) > 4000:
raise invalid("Некорректный текст сообщения")
raw_attachment_ids = payload.get("attachment_ids", [])
if (
not isinstance(raw_attachment_ids, list)
or len(raw_attachment_ids) > 10
):
raise invalid("Допускается список максимум из 10 вложений")
attachment_ids = [
parse_uuid(value)
for value in raw_attachment_ids
]
if len(set(attachment_ids)) != len(attachment_ids):
raise invalid("Вложения не должны повторяться")
if not text.strip() and not attachment_ids:
raise invalid("Сообщение должно содержать текст или вложение")
message = await create_message_once(
chat_uuid,
user["id"],
text,
keys[0],
attachment_ids=attachment_ids,
)
return json_response(message, 201)
@router.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, request: Request):
user, _ = await current_user(request)
chat_uuid, _ = await accessible_chat(
chat_id,
user["id"],
)
scope = f"messages:{chat_uuid}"
limit, after = pagination(request, scope)
rows = await store.list_messages(
chat_uuid,
limit,
after,
)
return page_response(rows, limit, scope)
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from fastapi.responses import Response
from app.auth import (
DUMMY_PASSWORD_HASH,
generate_token,
hash_token,
parse_basic_credentials,
verify_password,
)
from app.config import SESSION_TTL_SECONDS
from app.dependencies import current_user
from app.errors import invalid, unauthorized
from app.responses import json_response
from app.store import store
router = APIRouter()
@router.post("/api/v1/auth/sessions")
async def create_session(request: Request):
credentials = parse_basic_credentials(
request.headers.get("authorization")
)
if credentials is None:
raise unauthorized("Basic")
username, password = credentials
user = await store.get_user_for_login(username)
stored_hash = (
DUMMY_PASSWORD_HASH
if user is None
else user["password_hash"]
)
password_ok = await verify_password(stored_hash, password)
if user is None or not password_ok:
raise unauthorized("Basic")
if await request.body():
raise invalid("Тело запроса при входе не допускается")
token = generate_token()
session = await store.create_session(
user["id"],
hash_token(token),
SESSION_TTL_SECONDS,
)
public_user = {
field: user[field]
for field in ("id", "username", "display_name", "created_at")
}
return json_response(
{
"token": token,
"token_type": "Bearer",
"expires_at": session["expires_at"],
"user": public_user,
},
201,
)
@router.delete("/api/v1/auth/sessions/current")
async def revoke_session(request: Request):
_, token_digest = await current_user(request)
revoked = await store.revoke_session(token_digest)
if not revoked:
raise unauthorized()
return Response(status_code=204)
+59
View File
@@ -0,0 +1,59 @@
from __future__ import annotations
from fastapi import APIRouter, Request
from app.auth import USERNAME_RE, hash_password
from app.dependencies import current_user
from app.errors import ApiError, invalid
from app.responses import json_response
from app.store import store
from app.validation import read_payload, valid_text
router = APIRouter()
@router.post("/api/v1/users")
async def create_user(request: Request):
payload = await read_payload(
request,
{"username", "display_name", "password"},
)
username = payload["username"]
display_name = payload["display_name"]
password = payload["password"]
if (
not isinstance(username, str)
or USERNAME_RE.fullmatch(username) is None
):
raise invalid("Некорректный username")
if not valid_text(display_name, 100):
raise invalid("Некорректное display_name")
if not valid_text(password, 128) or len(password) < 12:
raise invalid("Пароль должен содержать от 12 до 128 символов")
password_digest = await hash_password(password)
user = await store.create_user(
username,
display_name,
password_digest,
)
if user is None:
raise ApiError(
409,
"conflict",
"Username уже занят",
)
return json_response(user, 201)
@router.get("/api/v1/users/me")
async def get_current_user(request: Request):
user, _ = await current_user(request)
return json_response(user)
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
import asyncio
import time
from app.errors import ApiError
from app.storage import check_storage
async def main() -> None:
deadline = time.monotonic() + 90
while True:
try:
await check_storage()
except ApiError:
if time.monotonic() >= deadline:
raise SystemExit(
"S3 readiness failed: bucket unavailable "
"or API credentials rejected"
) from None
print("Waiting for S3 bucket...", flush=True)
await asyncio.sleep(2)
else:
print(
"S3 bucket is accessible with API credentials",
flush=True,
)
return
if __name__ == "__main__":
asyncio.run(main())
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import asyncio
import os
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import (
BotoCoreError,
ClientError,
)
from app.errors import ApiError
_client = None
def _unavailable() -> ApiError:
return ApiError(
503,
"unavailable",
"Сервис временно недоступен",
)
def _credential(file_variable: str) -> str:
file_path = os.environ[file_variable]
value = Path(file_path).read_text().rstrip("\r\n")
if not value:
raise ValueError("Empty S3 credential file")
return value
def bucket_name() -> str:
return os.environ["S3_BUCKET"]
def get_client():
global _client
if _client is None:
_client = boto3.client(
"s3",
endpoint_url=os.environ["S3_ENDPOINT"],
aws_access_key_id=_credential("S3_ACCESS_KEY_ID_FILE"),
aws_secret_access_key=_credential("S3_SECRET_ACCESS_KEY_FILE"),
region_name=os.getenv("S3_REGION", "us-east-1"),
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=3,
read_timeout=10,
retries={
"mode": "standard",
"total_max_attempts": 2,
},
),
)
return _client
def _put(key: str, data: bytes, content_type: str) -> None:
get_client().put_object(
Bucket=bucket_name(),
Key=key,
Body=data,
ContentType=content_type,
)
def _get(key: str) -> bytes:
maximum = 10 * 1024 * 1024
response = get_client().get_object(
Bucket=bucket_name(),
Key=key,
)
body = response["Body"]
try:
expected_size = response["ContentLength"]
if not 1 <= expected_size <= maximum:
raise _unavailable()
data = body.read(maximum + 1)
if len(data) != expected_size or len(data) > maximum:
raise _unavailable()
return data
finally:
body.close()
async def put_object(
key: str,
data: bytes,
content_type: str,
) -> None:
try:
await asyncio.to_thread(_put, key, data, content_type)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
async def get_object(key: str) -> bytes:
try:
return await asyncio.to_thread(_get, key)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
def _check() -> None:
get_client().head_bucket(Bucket=bucket_name())
async def check_storage() -> None:
try:
await asyncio.to_thread(_check)
except (BotoCoreError, ClientError, OSError, KeyError, ValueError):
raise _unavailable() from None
+280
View File
@@ -0,0 +1,280 @@
from __future__ import annotations
from datetime import datetime
from uuid import UUID, uuid4
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from app.db import pool
class InvalidMembersError(Exception):
pass
class PostgresStore:
async def create_user(
self,
username: str,
display_name: str,
password_hash: str,
) -> dict | None:
try:
async with pool.connection() as conn:
cursor = await conn.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),
)
user = await cursor.fetchone()
return user
except UniqueViolation as exc:
if exc.diag.constraint_name == "users_username_unique":
return None
raise
async def get_user(self, user_id: UUID) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
)
return await cursor.fetchone()
async def get_user_for_login(self, username: str) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT id, username, display_name,
password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
)
return await cursor.fetchone()
async def create_chat(
self,
title: str,
member_ids: list[UUID],
) -> dict:
chat_id = uuid4()
try:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO chats (id, title)
VALUES (%s, %s)
RETURNING id, title, created_at
""",
(chat_id, title),
)
chat = await cursor.fetchone()
async with conn.cursor() as cursor:
await cursor.executemany(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (%s, %s)
""",
[(chat_id, user_id) for user_id in member_ids],
)
chat["member_ids"] = member_ids
return chat
except ForeignKeyViolation as exc:
raise InvalidMembersError from exc
async def get_accessible_chat(
self,
chat_id: UUID,
user_id: UUID,
) -> dict | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
WHERE c.id = %s
AND EXISTS (
SELECT 1
FROM chat_members AS access
WHERE access.chat_id = c.id
AND access.user_id = %s
)
""",
(chat_id, user_id),
)
return await cursor.fetchone()
async def list_chats(
self,
user_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [user_id]
after_sql = ""
if after is not None:
after_sql = "AND (c.created_at, c.id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id
FROM chat_members AS cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
) AS member_ids
FROM chats AS c
JOIN chat_members AS access
ON access.chat_id = c.id
WHERE access.user_id = %s
{after_sql}
ORDER BY c.created_at, c.id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_message(
self,
chat_id: UUID,
sender_id: UUID,
text: str,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(uuid4(), chat_id, sender_id, text),
)
message = await cursor.fetchone()
return message
async def list_messages(
self,
chat_id: UUID,
limit: int,
after: tuple[datetime, UUID] | None = None,
) -> list[dict]:
params: list[object] = [chat_id]
after_sql = ""
if after is not None:
after_sql = "AND (created_at, id) > (%s, %s)"
params.extend(after)
params.append(limit + 1)
async with pool.connection() as conn:
cursor = await conn.execute(
f"""
SELECT m.id, m.chat_id, m.sender_id,
m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments AS ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM messages AS m
WHERE m.chat_id = %s
{after_sql}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
return await cursor.fetchall()
async def create_session(
self,
user_id: UUID,
token_hash: str,
ttl_seconds: int,
) -> dict:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
INSERT INTO sessions (
token_hash, user_id, created_at, expires_at
)
VALUES (
%s, %s, statement_timestamp(),
statement_timestamp()
+ (%s * INTERVAL '1 second')
)
RETURNING expires_at
""",
(token_hash, user_id, ttl_seconds),
)
session = await cursor.fetchone()
return session
async def get_session_user_id(
self,
token_hash: str,
) -> UUID | None:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
SELECT user_id
FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
""",
(token_hash,),
)
row = await cursor.fetchone()
return None if row is None else row["user_id"]
async def revoke_session(self, token_hash: str) -> bool:
async with pool.connection() as conn:
cursor = await conn.execute(
"""
DELETE FROM sessions
WHERE token_hash = %s
AND expires_at > statement_timestamp()
RETURNING token_hash
""",
(token_hash,),
)
row = await cursor.fetchone()
return row is not None
store = PostgresStore()
+61
View File
@@ -0,0 +1,61 @@
from __future__ import annotations
from uuid import UUID
from fastapi import Request
from app.errors import ApiError, invalid
def parse_uuid(value: object) -> UUID:
if not isinstance(value, str):
raise invalid("Некорректный UUID")
try:
return UUID(value)
except ValueError:
raise invalid("Некорректный UUID") from None
def valid_text(value: object, maximum: int) -> bool:
return (
isinstance(value, str)
and 1 <= len(value) <= maximum
and bool(value.strip())
)
async def read_payload(
request: Request,
expected_fields: set[str],
optional_fields: set[str] | None = None,
) -> dict:
content_type = (
request.headers.get("content-type", "")
.split(";", 1)[0]
.strip()
.lower()
)
if content_type != "application/json":
raise ApiError(
415,
"unsupported_media_type",
"Требуется Content-Type: application/json",
)
try:
payload = await request.json()
except (ValueError, UnicodeError):
raise invalid("Некорректный JSON") from None
allowed_fields = expected_fields | (optional_fields or set())
if (
not isinstance(payload, dict)
or not expected_fields.issubset(payload)
or not set(payload).issubset(allowed_fields)
):
raise invalid("Некорректные поля запроса")
return payload