feat: initial microservices project structure
Services: - api: FastAPI gateway with JWT auth, async endpoints, WebSocket - worker-gpu: CUDA sentence-transformers, FAISS IVFFlat, Ollama LLM - worker-indexer: Winnowing+MinHash plagiarism detection, PDF/DOCX extraction - worker-notifier: SMTP email notifications - worker-gost: GOST 7.1-2003 and GOST R 7.0.5-2008 formatting Infrastructure: - docker-compose.yml (production) + docker-compose.dev.yml (hot reload) - Nginx reverse proxy + WebSocket support - PostgreSQL 16 with Alembic migrations - Elasticsearch 8 with Russian/English analyzers - MinIO, RabbitMQ, Redis, Ollama Frontend: - React 18 + Vite + TypeScript + TailwindCSS + Zustand + React Query v5 - 9 pages: Home, Search, Cabinet, Task, Check, Bibliography, Pricing, Login, Register Scripts: - Parser stubs: OpenAlex, КиберЛенинка, arXiv (Phase 0 - to be filled) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
0
services/api/app/core/__init__.py
Normal file
0
services/api/app/core/__init__.py
Normal file
39
services/api/app/core/celery_app.py
Normal file
39
services/api/app/core/celery_app.py
Normal file
@@ -0,0 +1,39 @@
|
||||
"""Celery приложение для API-диспатчера. Только определение — задачи находятся в воркерах."""
|
||||
|
||||
from celery import Celery
|
||||
|
||||
from app.config import settings
|
||||
|
||||
celery_app = Celery(
|
||||
"api_dispatcher",
|
||||
broker=settings.RABBITMQ_URL,
|
||||
backend=settings.REDIS_URL,
|
||||
)
|
||||
|
||||
celery_app.conf.update(
|
||||
task_serializer="json",
|
||||
result_serializer="json",
|
||||
accept_content=["json"],
|
||||
timezone="Europe/Moscow",
|
||||
enable_utc=True,
|
||||
task_track_started=True,
|
||||
# Маршрутизация задач по очередям воркеров
|
||||
task_routes={
|
||||
"gpu.*": {"queue": "queue.gpu"},
|
||||
"index.*": {"queue": "queue.index"},
|
||||
"notify.*": {"queue": "queue.notify"},
|
||||
"gost.*": {"queue": "queue.gost"},
|
||||
},
|
||||
# Настройки очередей
|
||||
task_queues={
|
||||
"queue.gpu": {"exchange": "queue.gpu", "routing_key": "queue.gpu"},
|
||||
"queue.index": {"exchange": "queue.index", "routing_key": "queue.index"},
|
||||
"queue.notify": {"exchange": "queue.notify", "routing_key": "queue.notify"},
|
||||
"queue.gost": {"exchange": "queue.gost", "routing_key": "queue.gost"},
|
||||
},
|
||||
# Результаты хранить 24 часа
|
||||
result_expires=86400,
|
||||
# Повторные попытки
|
||||
task_acks_late=True,
|
||||
task_reject_on_worker_lost=True,
|
||||
)
|
||||
167
services/api/app/core/rate_limiter.py
Normal file
167
services/api/app/core/rate_limiter.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""Redis-based rate limiter для проверки лимитов по тарифному плану."""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import redis
|
||||
|
||||
from app.config import settings
|
||||
|
||||
# Лимиты по тарифным планам
|
||||
PLAN_LIMITS: dict[str, dict[str, int | None]] = {
|
||||
"free": {
|
||||
"search_per_day": 10,
|
||||
"summarize_per_month": 3,
|
||||
"plagiarism_per_month": 1,
|
||||
"concurrent": 1,
|
||||
},
|
||||
"student": {
|
||||
"search_per_day": None, # None = безлимит
|
||||
"summarize_per_month": 30,
|
||||
"plagiarism_per_month": 10,
|
||||
"concurrent": 2,
|
||||
},
|
||||
"premium": {
|
||||
"search_per_day": None,
|
||||
"summarize_per_month": None,
|
||||
"plagiarism_per_month": 50,
|
||||
"concurrent": 5,
|
||||
},
|
||||
"science": {
|
||||
"search_per_day": None,
|
||||
"summarize_per_month": None,
|
||||
"plagiarism_per_month": None,
|
||||
"concurrent": 10,
|
||||
},
|
||||
}
|
||||
|
||||
# Маппинг действий на ключи лимитов
|
||||
ACTION_TO_LIMIT: dict[str, tuple[str, str]] = {
|
||||
"search": ("search_per_day", "day"),
|
||||
"summarize": ("summarize_per_month", "month"),
|
||||
"plagiarism": ("plagiarism_per_month", "month"),
|
||||
"gost": ("gost_per_month", "month"), # ГОСТ всегда разрешён
|
||||
}
|
||||
|
||||
|
||||
def get_redis_client() -> redis.Redis:
|
||||
"""Создать синхронный Redis клиент."""
|
||||
return redis.from_url(settings.REDIS_URL, decode_responses=True)
|
||||
|
||||
|
||||
def _get_period_key(period: str) -> str:
|
||||
"""Получить строку периода для Redis ключа."""
|
||||
now = datetime.now(timezone.utc)
|
||||
if period == "day":
|
||||
return now.strftime("%Y-%m-%d")
|
||||
elif period == "month":
|
||||
return now.strftime("%Y-%m")
|
||||
return now.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def check_and_increment_limit(user_id: int, action: str, plan: str) -> dict:
|
||||
"""
|
||||
Проверить лимит и инкрементировать счётчик.
|
||||
|
||||
Args:
|
||||
user_id: ID пользователя
|
||||
action: Действие (search, plagiarism, summarize, gost)
|
||||
plan: Тарифный план пользователя
|
||||
|
||||
Returns:
|
||||
dict с полями:
|
||||
- allowed: bool — разрешено ли действие
|
||||
- current: int — текущее количество использований
|
||||
- limit: int | None — лимит (None = безлимит)
|
||||
- remaining: int | None — осталось использований
|
||||
- reset_at: str — когда сбрасывается счётчик
|
||||
"""
|
||||
limits = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
|
||||
|
||||
if action not in ACTION_TO_LIMIT:
|
||||
# Неизвестное действие — разрешаем
|
||||
return {"allowed": True, "current": 0, "limit": None, "remaining": None}
|
||||
|
||||
limit_key, period = ACTION_TO_LIMIT[action]
|
||||
limit_value = limits.get(limit_key)
|
||||
|
||||
# Безлимитный план
|
||||
if limit_value is None:
|
||||
return {
|
||||
"allowed": True,
|
||||
"current": 0,
|
||||
"limit": None,
|
||||
"remaining": None,
|
||||
"reset_at": None,
|
||||
}
|
||||
|
||||
period_str = _get_period_key(period)
|
||||
redis_key = f"rate:{user_id}:{action}:{period_str}"
|
||||
|
||||
r = get_redis_client()
|
||||
|
||||
# Атомарно инкрементировать
|
||||
pipe = r.pipeline()
|
||||
pipe.incr(redis_key)
|
||||
# Устанавливаем TTL: для дня — 86400 сек, для месяца — 32 дня
|
||||
ttl = 86400 if period == "day" else 86400 * 32
|
||||
pipe.expire(redis_key, ttl)
|
||||
results = pipe.execute()
|
||||
|
||||
current = results[0]
|
||||
|
||||
if current > limit_value:
|
||||
# Декрементировать обратно (не считать запрещённые)
|
||||
r.decr(redis_key)
|
||||
current -= 1
|
||||
return {
|
||||
"allowed": False,
|
||||
"current": current,
|
||||
"limit": limit_value,
|
||||
"remaining": 0,
|
||||
"reset_at": period_str,
|
||||
}
|
||||
|
||||
return {
|
||||
"allowed": True,
|
||||
"current": current,
|
||||
"limit": limit_value,
|
||||
"remaining": limit_value - current,
|
||||
"reset_at": period_str,
|
||||
}
|
||||
|
||||
|
||||
def check_concurrent_limit(user_id: int, plan: str) -> bool:
|
||||
"""
|
||||
Проверить лимит одновременных задач.
|
||||
|
||||
Returns:
|
||||
True если можно создать новую задачу, False если превышен лимит.
|
||||
"""
|
||||
limits = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
|
||||
max_concurrent = limits.get("concurrent", 1)
|
||||
|
||||
r = get_redis_client()
|
||||
key = f"concurrent:{user_id}"
|
||||
current = r.get(key)
|
||||
|
||||
return (current is None) or (int(current) < max_concurrent)
|
||||
|
||||
|
||||
def increment_concurrent(user_id: int) -> None:
|
||||
"""Увеличить счётчик одновременных задач (при создании задачи)."""
|
||||
r = get_redis_client()
|
||||
key = f"concurrent:{user_id}"
|
||||
pipe = r.pipeline()
|
||||
pipe.incr(key)
|
||||
pipe.expire(key, 3600) # Автосброс через 1 час
|
||||
pipe.execute()
|
||||
|
||||
|
||||
def decrement_concurrent(user_id: int) -> None:
|
||||
"""Уменьшить счётчик одновременных задач (при завершении задачи)."""
|
||||
r = get_redis_client()
|
||||
key = f"concurrent:{user_id}"
|
||||
current = r.get(key)
|
||||
if current and int(current) > 0:
|
||||
r.decr(key)
|
||||
110
services/api/app/core/security.py
Normal file
110
services/api/app/core/security.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""Утилиты безопасности: JWT, хэширование паролей, dependency для получения текущего пользователя."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database import get_db
|
||||
|
||||
# Контекст хэширования паролей (bcrypt)
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
# OAuth2 схема
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Хэшировать пароль через bcrypt."""
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Проверить соответствие пароля его хэшу."""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
|
||||
"""Создать JWT токен доступа."""
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + (
|
||||
expires_delta or timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
)
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
|
||||
def verify_token(token: str) -> dict[str, Any]:
|
||||
"""
|
||||
Декодировать и верифицировать JWT токен.
|
||||
|
||||
Raises:
|
||||
HTTPException: если токен невалиден или просрочен.
|
||||
"""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
user_id: int | None = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Неверный токен аутентификации",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return payload
|
||||
except JWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Невалидный или просроченный токен",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
FastAPI dependency: получить текущего авторизованного пользователя из JWT токена.
|
||||
|
||||
Raises:
|
||||
HTTPException 401: если токен невалиден.
|
||||
HTTPException 404: если пользователь не найден.
|
||||
"""
|
||||
from app.models.user import User
|
||||
|
||||
payload = verify_token(token)
|
||||
user_id: int = int(payload.get("sub"))
|
||||
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Пользователь не найден",
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_verified_user(
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
"""
|
||||
FastAPI dependency: только верифицированные пользователи.
|
||||
|
||||
Raises:
|
||||
HTTPException 403: если email не подтверждён.
|
||||
"""
|
||||
if not current_user.is_verified:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Необходимо подтвердить email адрес",
|
||||
)
|
||||
return current_user
|
||||
86
services/api/app/core/websocket_manager.py
Normal file
86
services/api/app/core/websocket_manager.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""WebSocket менеджер для real-time обновлений статуса задач."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import WebSocket
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Менеджер WebSocket соединений с поддержкой подписки на задачи."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# task_id -> список активных соединений
|
||||
self._connections: dict[str, list[WebSocket]] = {}
|
||||
|
||||
async def connect(self, task_id: str, websocket: WebSocket) -> None:
|
||||
"""Принять WebSocket соединение и зарегистрировать его для задачи."""
|
||||
await websocket.accept()
|
||||
if task_id not in self._connections:
|
||||
self._connections[task_id] = []
|
||||
self._connections[task_id].append(websocket)
|
||||
logger.info(f"WebSocket подключён к задаче {task_id!r}")
|
||||
|
||||
def disconnect(self, task_id: str, websocket: WebSocket) -> None:
|
||||
"""Удалить соединение из реестра."""
|
||||
if task_id in self._connections:
|
||||
try:
|
||||
self._connections[task_id].remove(websocket)
|
||||
except ValueError:
|
||||
pass
|
||||
if not self._connections[task_id]:
|
||||
del self._connections[task_id]
|
||||
logger.info(f"WebSocket отключён от задачи {task_id!r}")
|
||||
|
||||
async def send_task_update(self, task_id: str, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
Отправить обновление статуса задачи всем подключённым клиентам.
|
||||
|
||||
Args:
|
||||
task_id: ID задачи
|
||||
data: Словарь с обновлением (status, queue_position, result и т.д.)
|
||||
"""
|
||||
connections = self._connections.get(task_id, [])
|
||||
if not connections:
|
||||
return
|
||||
|
||||
message = json.dumps(data, ensure_ascii=False, default=str)
|
||||
dead_connections = []
|
||||
|
||||
for websocket in connections:
|
||||
try:
|
||||
await websocket.send_text(message)
|
||||
except Exception as e:
|
||||
logger.warning(f"Ошибка отправки WebSocket сообщения: {e}")
|
||||
dead_connections.append(websocket)
|
||||
|
||||
# Очистить мёртвые соединения
|
||||
for ws in dead_connections:
|
||||
self.disconnect(task_id, ws)
|
||||
|
||||
async def broadcast(self, data: dict[str, Any]) -> None:
|
||||
"""Отправить сообщение всем подключённым клиентам."""
|
||||
message = json.dumps(data, ensure_ascii=False, default=str)
|
||||
all_dead = []
|
||||
|
||||
for task_id, connections in self._connections.items():
|
||||
for websocket in connections:
|
||||
try:
|
||||
await websocket.send_text(message)
|
||||
except Exception:
|
||||
all_dead.append((task_id, websocket))
|
||||
|
||||
for task_id, ws in all_dead:
|
||||
self.disconnect(task_id, ws)
|
||||
|
||||
@property
|
||||
def active_connections_count(self) -> int:
|
||||
"""Количество активных WebSocket соединений."""
|
||||
return sum(len(conns) for conns in self._connections.values())
|
||||
|
||||
|
||||
# Глобальный экземпляр менеджера
|
||||
ws_manager = ConnectionManager()
|
||||
Reference in New Issue
Block a user