fix problem from claude

This commit is contained in:
SlimusMinus
2026-10-20 00:37:43 +03:00
parent f01f776d32
commit 28d91ce6d4
31 changed files with 994 additions and 284 deletions

View File

@@ -0,0 +1,88 @@
import json
from typing import Callable
# Запас под заголовки multipart (boundary, Content-Disposition и т.п.)
MULTIPART_OVERHEAD = 64 * 1024
class _BodyTooLarge(Exception):
pass
class BodySizeLimitMiddleware:
"""
Отклоняет слишком большие тела запросов с 413, не дочитывая их.
Без этого Starlette сначала целиком принимает multipart (с диска), и только
потом роутер видит размер — гигабайтный аплоад забивает диск и канал.
Content-Length проверяется сразу; для chunked-запросов байты считаются
на лету.
"""
def __init__(self, app, limit_for_path: Callable[[str], int]):
self.app = app
self.limit_for_path = limit_for_path
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
limit = self.limit_for_path(scope.get("path", ""))
content_length = None
for name, value in scope.get("headers", []):
if name == b"content-length":
content_length = value
break
if content_length is not None:
try:
declared = int(content_length)
except ValueError:
await self._reject(send, 400, "INVALID_REQUEST", "Invalid Content-Length")
return
if declared > limit:
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
return
received = 0
rejected = False
async def limited_receive():
nonlocal received, rejected
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > limit:
rejected = True
raise _BodyTooLarge()
return message
async def guarded_send(message):
# После превышения лимита ответ приложения (обычно 400 «ошибка
# разбора тела») подменяем на 413
if not rejected:
await send(message)
try:
await self.app(scope, limited_receive, guarded_send)
except _BodyTooLarge:
pass
if rejected:
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
@staticmethod
async def _reject(send, status: int, code: str, message: str):
body = json.dumps({"code": code, "message": message}).encode()
await send({
"type": "http.response.start",
"status": status,
"headers": [
(b"content-type", b"application/json"),
(b"content-length", str(len(body)).encode()),
(b"connection", b"close"),
],
})
await send({"type": "http.response.body", "body": body})

View File

@@ -0,0 +1,29 @@
import threading
from contextlib import contextmanager
from app.config.settings import settings
from app.exceptions.service_busy_exception import ServiceBusyException
class InferenceLimiter:
"""Ограничивает число одновременных прогонов моделей (синхронные эндпоинты)."""
def __init__(self, name: str, max_concurrency: int):
self.name = name
self._semaphore = threading.BoundedSemaphore(max(1, max_concurrency))
@contextmanager
def slot(self, timeout: float | None = None):
timeout = settings.INFERENCE_QUEUE_TIMEOUT if timeout is None else timeout
if not self._semaphore.acquire(timeout=timeout):
raise ServiceBusyException(
f"{self.name} moderation is busy, retry later"
)
try:
yield
finally:
self._semaphore.release()
image_limiter = InferenceLimiter("Image", settings.IMAGE_MAX_CONCURRENCY)
text_limiter = InferenceLimiter("Text", settings.TEXT_MAX_CONCURRENCY)

View File

@@ -1,4 +1,5 @@
from functools import lru_cache
from pathlib import Path
from app.ml.image.clip_classifier import ClipClassifier
from app.ml.image.image_classifier import ImageClassifier
@@ -11,6 +12,12 @@ from app.moderation.profanity.lemmatizer import Lemmatizer
from app.services.image_moderation_service import ImageModerationService
from app.services.text_moderation_service import TextModerationService
# Путь от пакета, а не от текущей директории: иначе запуск не из
# ai-moderation/ (тесты, IDE) падает с FileNotFoundError
PROFANITY_WORDS_PATH = (
Path(__file__).resolve().parent.parent / "resources" / "profanity_words.txt"
)
@lru_cache
def get_clip_classifier() -> ClipClassifier:
@@ -26,7 +33,7 @@ def get_text_classifier() -> TextClassifier:
def get_profanity_detector() -> ProfanityDetector:
return ProfanityDetector(
dictionary=ProfanityDictionary(
file_path="app/resources/profanity_words.txt"
file_path=PROFANITY_WORDS_PATH
),
lemmatizer=Lemmatizer()
)
@@ -62,4 +69,4 @@ def get_image_moderation_service() -> ImageModerationService:
validator=get_image_validator(),
clip_classifier=get_clip_classifier(),
weapon_detector=get_weapon_detector()
)
)

View File

@@ -0,0 +1,18 @@
import hmac
from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader
from app.config.settings import settings
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def verify_api_key(api_key: str | None = Security(api_key_header)) -> None:
"""Проверка общего секрета с бэкендом. Выключена, пока API_KEY не задан."""
if settings.API_KEY is None:
return
expected = settings.API_KEY.get_secret_value().encode()
if api_key is None or not hmac.compare_digest(api_key.encode(), expected):
raise HTTPException(status_code=401, detail="Invalid API key")