forked from mtusi2026/mtusi2026lab5
lab5: асинхронный воркер, брокер сообщений
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
|
||||
DATABASE_URL = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql+asyncpg://messenger:messenger_password@db:5432/messenger_db",
|
||||
)
|
||||
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
CODE_MAP = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
|
||||
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://minio:9000")
|
||||
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "minioadmin")
|
||||
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "minioadmin")
|
||||
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from app.config import DATABASE_URL
|
||||
|
||||
engine = create_async_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800,
|
||||
echo=False,
|
||||
)
|
||||
|
||||
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
@@ -0,0 +1,6 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.database import async_session_maker
|
||||
|
||||
async def get_session():
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,37 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from app.config import CODE_MAP
|
||||
|
||||
|
||||
def error_response(request: Request, status_code: int, code: str, message: str, extra_headers: dict = None):
|
||||
request_id = getattr(request.state, "request_id", "unknown")
|
||||
|
||||
|
||||
headers = {"X-Request-Id": request_id}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
code = CODE_MAP.get(exc.status_code, "internal_error")
|
||||
return error_response(request, exc.status_code, code, str(exc.detail), extra_headers=exc.headers)
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Ошибка валидации данных")
|
||||
|
||||
async def internal_error_handler(request: Request, exc: Exception):
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
@@ -0,0 +1,62 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
MAX_INPUT_PIXELS = 20_000_000
|
||||
|
||||
|
||||
def main():
|
||||
input_path = Path(sys.argv[1])
|
||||
output_dir = Path(sys.argv[2])
|
||||
|
||||
try:
|
||||
with Image.open(input_path) as source:
|
||||
if source.width * source.height > MAX_INPUT_PIXELS:
|
||||
return 20
|
||||
|
||||
source.load()
|
||||
img = source.convert("RGB")
|
||||
|
||||
crop = ImageOps.fit(
|
||||
img,
|
||||
(128, 128),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5)
|
||||
)
|
||||
|
||||
crop.save(
|
||||
output_dir / "crop.jpg",
|
||||
format="JPEG",
|
||||
quality=85
|
||||
)
|
||||
|
||||
img.save(
|
||||
output_dir / "optimized.webp",
|
||||
format="WEBP",
|
||||
quality=80,
|
||||
method=6
|
||||
)
|
||||
|
||||
img.thumbnail((256, 256))
|
||||
|
||||
img.save(
|
||||
output_dir / "thumbnail.jpg",
|
||||
format="JPEG",
|
||||
quality=85
|
||||
)
|
||||
|
||||
except (
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
ValueError,
|
||||
Image.DecompressionBombError,
|
||||
):
|
||||
return 21
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,336 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import S3_BUCKET
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.outbox import OutboxEvent
|
||||
from app.outbox_dispatcher import session_maker
|
||||
from app.worker import minio_client
|
||||
|
||||
|
||||
IMAGE_SIZES = [512, 1024, 2048]
|
||||
|
||||
|
||||
def make_image(size):
|
||||
image = Image.effect_noise((size, size), 80).convert("RGB")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="JPEG", quality=85)
|
||||
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def percentile(values, percent):
|
||||
values = sorted(values)
|
||||
|
||||
if not values:
|
||||
return None
|
||||
|
||||
position = (len(values) - 1) * percent / 100
|
||||
lower = int(position)
|
||||
upper = min(lower + 1, len(values) - 1)
|
||||
|
||||
return values[lower] + (
|
||||
values[upper] - values[lower]
|
||||
) * (position - lower)
|
||||
|
||||
|
||||
async def get_source():
|
||||
async with session_maker() as session:
|
||||
result = await session.execute(
|
||||
select(Attachment)
|
||||
.where(Attachment.status == "ready")
|
||||
.order_by(Attachment.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
source = result.scalar_one_or_none()
|
||||
|
||||
if source is None:
|
||||
raise RuntimeError(
|
||||
"Нет готовой фотографии для создания тестовых записей"
|
||||
)
|
||||
|
||||
return source.chat_id, source.user_id
|
||||
|
||||
|
||||
async def create_jobs(count_per_size, run_id):
|
||||
chat_id, user_id = await get_source()
|
||||
|
||||
jobs = []
|
||||
|
||||
for size in IMAGE_SIZES:
|
||||
data = make_image(size)
|
||||
|
||||
print(
|
||||
f"[LOAD] Изображение {size}x{size}: "
|
||||
f"{len(data) / 1024:.1f} KB",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
for index in range(count_per_size):
|
||||
key = f"benchmark/{run_id}/{size}_{index}.jpg"
|
||||
|
||||
minio_client.put_object(
|
||||
S3_BUCKET,
|
||||
key,
|
||||
io.BytesIO(data),
|
||||
len(data),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
|
||||
jobs.append({
|
||||
"size": size,
|
||||
"key": key,
|
||||
"data": data,
|
||||
})
|
||||
|
||||
async with session_maker() as session:
|
||||
async with session.begin():
|
||||
for job in jobs:
|
||||
data = job["data"]
|
||||
|
||||
attachment = Attachment(
|
||||
object_key=job["key"],
|
||||
filename=f"benchmark_{job['size']}.jpg",
|
||||
mime_type="image/jpeg",
|
||||
size_bytes=len(data),
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
sha256=hashlib.sha256(data).hexdigest(),
|
||||
status="queued",
|
||||
)
|
||||
|
||||
session.add(attachment)
|
||||
await session.flush()
|
||||
|
||||
session.add(
|
||||
OutboxEvent(attachment_id=attachment.id)
|
||||
)
|
||||
|
||||
job["id"] = attachment.id
|
||||
del job["data"]
|
||||
|
||||
return jobs
|
||||
|
||||
|
||||
async def monitor_jobs(jobs, timeout):
|
||||
ids = [job["id"] for job in jobs]
|
||||
|
||||
started = time.perf_counter()
|
||||
last_report = started
|
||||
|
||||
first_processing = {}
|
||||
ready_times = {}
|
||||
failed = set()
|
||||
|
||||
peak_processing = 0
|
||||
|
||||
while True:
|
||||
now = time.perf_counter()
|
||||
elapsed = now - started
|
||||
|
||||
async with session_maker() as session:
|
||||
result = await session.execute(
|
||||
select(Attachment.id, Attachment.status)
|
||||
.where(Attachment.id.in_(ids))
|
||||
)
|
||||
|
||||
statuses = result.all()
|
||||
|
||||
processing_count = 0
|
||||
|
||||
for attachment_id, status in statuses:
|
||||
if status == "processing":
|
||||
processing_count += 1
|
||||
|
||||
if attachment_id not in first_processing:
|
||||
first_processing[attachment_id] = elapsed
|
||||
|
||||
elif status == "ready":
|
||||
if attachment_id not in ready_times:
|
||||
ready_times[attachment_id] = elapsed
|
||||
|
||||
elif status == "failed":
|
||||
failed.add(attachment_id)
|
||||
|
||||
peak_processing = max(
|
||||
peak_processing,
|
||||
processing_count,
|
||||
)
|
||||
|
||||
completed = len(ready_times) + len(failed)
|
||||
|
||||
if now - last_report >= 5:
|
||||
print(
|
||||
f"[LOAD] Готово: {len(ready_times)}/{len(jobs)}, "
|
||||
f"failed={len(failed)}, "
|
||||
f"processing={processing_count}, "
|
||||
f"elapsed={elapsed:.1f}s",
|
||||
flush=True,
|
||||
)
|
||||
last_report = now
|
||||
|
||||
if completed == len(jobs):
|
||||
break
|
||||
|
||||
if elapsed >= timeout:
|
||||
print("[LOAD] Достигнут таймаут", flush=True)
|
||||
break
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
return {
|
||||
"ready_times": ready_times,
|
||||
"first_processing": first_processing,
|
||||
"failed": failed,
|
||||
"peak_processing": peak_processing,
|
||||
"elapsed": time.perf_counter() - started,
|
||||
}
|
||||
|
||||
|
||||
def save_results(jobs, results, run_id):
|
||||
output = Path(f"benchmark_{run_id}.csv")
|
||||
|
||||
with output.open("w", newline="") as file:
|
||||
writer = csv.writer(file)
|
||||
|
||||
writer.writerow([
|
||||
"attachment_id",
|
||||
"image_size",
|
||||
"status",
|
||||
"queue_lag_estimate_s",
|
||||
"time_to_ready_s",
|
||||
])
|
||||
|
||||
for job in jobs:
|
||||
attachment_id = job["id"]
|
||||
|
||||
ready = results["ready_times"].get(attachment_id)
|
||||
lag = results["first_processing"].get(attachment_id)
|
||||
|
||||
status = (
|
||||
"ready" if ready is not None
|
||||
else "failed" if attachment_id in results["failed"]
|
||||
else "unfinished"
|
||||
)
|
||||
|
||||
writer.writerow([
|
||||
str(attachment_id),
|
||||
job["size"],
|
||||
status,
|
||||
round(lag, 3) if lag is not None else "",
|
||||
round(ready, 3) if ready is not None else "",
|
||||
])
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def print_results(jobs, results):
|
||||
ready_times = results["ready_times"]
|
||||
first_processing = results["first_processing"]
|
||||
|
||||
total = len(jobs)
|
||||
completed = len(ready_times)
|
||||
|
||||
throughput = (
|
||||
completed / results["elapsed"]
|
||||
if results["elapsed"] > 0
|
||||
else 0
|
||||
)
|
||||
|
||||
print("\n========== BENCHMARK RESULTS ==========")
|
||||
print(f"Total jobs: {total}")
|
||||
print(f"Ready: {completed}")
|
||||
print(f"Failed: {len(results['failed'])}")
|
||||
print(f"Duration: {results['elapsed']:.2f} s")
|
||||
print(f"Throughput: {throughput:.2f} images/s")
|
||||
print(f"Peak observed processing: {results['peak_processing']}")
|
||||
|
||||
for size in IMAGE_SIZES:
|
||||
size_jobs = [
|
||||
job for job in jobs
|
||||
if job["size"] == size
|
||||
]
|
||||
|
||||
times = [
|
||||
ready_times[job["id"]]
|
||||
for job in size_jobs
|
||||
if job["id"] in ready_times
|
||||
]
|
||||
|
||||
lags = [
|
||||
first_processing[job["id"]]
|
||||
for job in size_jobs
|
||||
if job["id"] in first_processing
|
||||
]
|
||||
|
||||
print(f"\nImage size: {size}x{size}")
|
||||
print(f"Completed: {len(times)}/{len(size_jobs)}")
|
||||
|
||||
if times:
|
||||
print(f"Mean ready: {statistics.mean(times):.2f} s")
|
||||
print(f"P95 ready: {percentile(times, 95):.2f} s")
|
||||
|
||||
if lags:
|
||||
print(f"Mean observed queue lag: {statistics.mean(lags):.2f} s")
|
||||
print(f"Queue lag samples: {len(lags)}/{len(size_jobs)}")
|
||||
|
||||
print("\n=======================================")
|
||||
|
||||
|
||||
async def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument(
|
||||
"--count",
|
||||
type=int,
|
||||
default=10,
|
||||
help="Количество изображений каждого размера",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--timeout",
|
||||
type=int,
|
||||
default=300,
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.count < 1 or args.timeout < 1:
|
||||
parser.error("--count и --timeout должны быть положительными")
|
||||
|
||||
run_id = uuid.uuid4().hex[:8]
|
||||
|
||||
print(f"[LOAD] Run ID: {run_id}")
|
||||
print("[LOAD] Подготовка изображений...")
|
||||
|
||||
jobs = await create_jobs(args.count, run_id)
|
||||
|
||||
print(f"[LOAD] Создано заданий: {len(jobs)}")
|
||||
print("[LOAD] Ожидание обработки...")
|
||||
|
||||
results = await monitor_jobs(jobs, args.timeout)
|
||||
|
||||
print_results(jobs, results)
|
||||
|
||||
output = save_results(jobs, results, run_id)
|
||||
|
||||
print(f"\nCSV: {output}")
|
||||
|
||||
if len(results["ready_times"]) != len(jobs):
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi import HTTPException
|
||||
import uuid
|
||||
from app.middleware import RequestIdMiddleware
|
||||
from app.exceptions import http_exception_handler, validation_exception_handler
|
||||
from app.routers import health, users, chats, messages, auth, attachments
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.1.0",
|
||||
)
|
||||
|
||||
INSTANCE_ID = str(uuid.uuid4())
|
||||
@app.middleware("http")
|
||||
async def add_instance_id_header(request, call_next):
|
||||
response = await call_next(request)
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
app.add_exception_handler(HTTPException, http_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(attachments.router_upload)
|
||||
app.include_router(attachments.router_download)
|
||||
@@ -0,0 +1,11 @@
|
||||
import uuid as uuid_lib
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request, call_next):
|
||||
request_id = str(uuid_lib.uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
@@ -0,0 +1,48 @@
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, Integer, ForeignKey, DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
|
||||
object_key: Mapped[str] = mapped_column(String, unique=True)
|
||||
filename: Mapped[str] = mapped_column(String)
|
||||
mime_type: Mapped[str] = mapped_column(String)
|
||||
size_bytes: Mapped[int] = mapped_column(Integer)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("chats.id"))
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
sha256: Mapped[str] = mapped_column(String, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now()
|
||||
)
|
||||
|
||||
status: Mapped[str] = mapped_column(String, default="queued")
|
||||
error_code: Mapped[str] = mapped_column(String, nullable=True)
|
||||
|
||||
lease_expires_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True
|
||||
)
|
||||
|
||||
thumbnail_key: Mapped[str] = mapped_column(String, nullable=True)
|
||||
thumbnail_sha256: Mapped[str] = mapped_column(String, nullable=True)
|
||||
thumbnail_size_bytes: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
thumbnail_width: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
thumbnail_height: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
|
||||
crop_key: Mapped[str] = mapped_column(String, nullable=True)
|
||||
webp_key: Mapped[str] = mapped_column(String, nullable=True)
|
||||
@@ -0,0 +1,4 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
@@ -0,0 +1,35 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, ForeignKey, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
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), server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
|
||||
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="CASCADE"),
|
||||
primary_key=True,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Text, DateTime, ForeignKey, Index, func, JSON
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
attachment_ids: Mapped[list] = mapped_column(JSON, default=list)
|
||||
|
||||
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),
|
||||
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
import uuid
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.attachment import Base
|
||||
|
||||
|
||||
class OutboxEvent(Base):
|
||||
__tablename__ = "outbox_events"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
primary_key=True,
|
||||
default=uuid.uuid4
|
||||
)
|
||||
|
||||
attachment_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("attachments.id"),
|
||||
nullable=False
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
nullable=False
|
||||
)
|
||||
|
||||
published_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import String, DateTime, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
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), unique=True, nullable=False, index=True
|
||||
)
|
||||
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import aio_pika
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.config import DATABASE_URL
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.outbox import OutboxEvent
|
||||
from app.models.user import User
|
||||
|
||||
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
|
||||
QUEUE_NAME = "image_tasks"
|
||||
POLL_INTERVAL_SECONDS = 1
|
||||
|
||||
engine = create_async_engine(DATABASE_URL)
|
||||
session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
async def recover_expired_lease():
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
async with session_maker() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
select(Attachment)
|
||||
.where(
|
||||
Attachment.status == "processing",
|
||||
Attachment.lease_expires_at.is_not(None),
|
||||
Attachment.lease_expires_at <= now,
|
||||
)
|
||||
.order_by(Attachment.lease_expires_at)
|
||||
.limit(1)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
|
||||
att = result.scalar_one_or_none()
|
||||
|
||||
if att is None:
|
||||
return False
|
||||
|
||||
att.status = "queued"
|
||||
att.lease_expires_at = None
|
||||
|
||||
session.add(
|
||||
OutboxEvent(attachment_id=att.id)
|
||||
)
|
||||
|
||||
attachment_id = att.id
|
||||
|
||||
print(f"[Outbox] Recovered expired lease: {attachment_id}", flush=True)
|
||||
return True
|
||||
|
||||
|
||||
async def dispatch_one(channel):
|
||||
async with session_maker() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
select(OutboxEvent)
|
||||
.where(OutboxEvent.published_at.is_(None))
|
||||
.order_by(OutboxEvent.created_at, OutboxEvent.id)
|
||||
.limit(1)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
|
||||
event = result.scalar_one_or_none()
|
||||
|
||||
if event is None:
|
||||
return False
|
||||
|
||||
confirmation = await channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=json.dumps(
|
||||
{"attachment_id": str(event.attachment_id)}
|
||||
).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=str(event.id),
|
||||
content_type="application/json",
|
||||
),
|
||||
routing_key=QUEUE_NAME,
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
if confirmation is False:
|
||||
raise RuntimeError("RabbitMQ did not confirm publication")
|
||||
|
||||
event.published_at = datetime.now(timezone.utc)
|
||||
|
||||
print(f"[Outbox] Published {event.attachment_id}", flush=True)
|
||||
return True
|
||||
|
||||
|
||||
async def main():
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
connection = await aio_pika.connect_robust(RABBITMQ_URL)
|
||||
|
||||
async with connection:
|
||||
channel = await connection.channel(
|
||||
publisher_confirms=True,
|
||||
on_return_raises=True,
|
||||
)
|
||||
|
||||
await channel.declare_queue(
|
||||
QUEUE_NAME,
|
||||
durable=True,
|
||||
)
|
||||
|
||||
while True:
|
||||
recovered = await recover_expired_lease()
|
||||
published = await dispatch_one(channel)
|
||||
|
||||
if not recovered and not published:
|
||||
await asyncio.sleep(POLL_INTERVAL_SECONDS)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
except Exception as exc:
|
||||
print(
|
||||
f"[Outbox] Retry after error: {type(exc).__name__}",
|
||||
flush=True,
|
||||
)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,20 @@
|
||||
def paginate(items: list, limit: int, cursor: str | None):
|
||||
start = 0
|
||||
if cursor is not None:
|
||||
try:
|
||||
start = int(cursor)
|
||||
except ValueError:
|
||||
start = 0
|
||||
|
||||
if start < 0:
|
||||
start = 0
|
||||
|
||||
page = items[start : start + limit]
|
||||
next_index = start + limit
|
||||
|
||||
if next_index < len(items):
|
||||
next_cursor = str(next_index)
|
||||
else:
|
||||
next_cursor = None
|
||||
|
||||
return page, next_cursor
|
||||
@@ -0,0 +1,9 @@
|
||||
import redis.asyncio as redis
|
||||
from app.config import REDIS_URL
|
||||
|
||||
redis_client = redis.from_url(
|
||||
REDIS_URL,
|
||||
decode_responses=True,
|
||||
socket_timeout=3,
|
||||
socket_connect_timeout=3,
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.config import DATABASE_URL
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.outbox import OutboxEvent
|
||||
from app.models.user import User
|
||||
from app.models.chat import Chat, ChatMember
|
||||
|
||||
|
||||
RETRYABLE_ERROR_CODES = {
|
||||
"s3_download_error",
|
||||
"s3_upload_error",
|
||||
"image_processing_timeout",
|
||||
"image_processor_start_error",
|
||||
"image_processor_error",
|
||||
"image_processor_output_error",
|
||||
"worker_error",
|
||||
}
|
||||
|
||||
|
||||
async def replay_failed(attachment_id: uuid.UUID):
|
||||
engine = create_async_engine(DATABASE_URL)
|
||||
session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
try:
|
||||
async with session_maker() as session:
|
||||
async with session.begin():
|
||||
att = await session.get(
|
||||
Attachment,
|
||||
attachment_id,
|
||||
with_for_update=True,
|
||||
)
|
||||
|
||||
if att is None:
|
||||
print("Файл не найден")
|
||||
return
|
||||
|
||||
if att.status != "failed":
|
||||
print(f"Replay запрещён: status={att.status}")
|
||||
return
|
||||
|
||||
if att.error_code not in RETRYABLE_ERROR_CODES:
|
||||
print(
|
||||
f"Replay запрещён: error_code={att.error_code}"
|
||||
)
|
||||
return
|
||||
|
||||
pending = await session.scalar(
|
||||
select(OutboxEvent.id)
|
||||
.where(
|
||||
OutboxEvent.attachment_id == attachment_id,
|
||||
OutboxEvent.published_at.is_(None),
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
if pending is not None:
|
||||
print("Задание уже ожидает публикации")
|
||||
return
|
||||
|
||||
att.status = "queued"
|
||||
att.error_code = None
|
||||
|
||||
session.add(
|
||||
OutboxEvent(attachment_id=attachment_id)
|
||||
)
|
||||
|
||||
print(f"Задание {attachment_id} отправлено на повторную обработку")
|
||||
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("Использование: python -m app.replay_failed UUID")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
attachment_id = uuid.UUID(sys.argv[1])
|
||||
except ValueError:
|
||||
print("Некорректный UUID")
|
||||
sys.exit(1)
|
||||
|
||||
asyncio.run(replay_failed(attachment_id))
|
||||
@@ -0,0 +1,286 @@
|
||||
import uuid
|
||||
import filetype
|
||||
import io
|
||||
import hashlib
|
||||
from datetime import datetime, timezone
|
||||
from PIL import Image
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func, text
|
||||
|
||||
from app.dependencies import get_session
|
||||
from app.security import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.outbox import OutboxEvent
|
||||
from app.models.chat import ChatMember
|
||||
from app.storage import minio_client, BUCKET
|
||||
|
||||
|
||||
router_upload = APIRouter(
|
||||
prefix="/api/v1/chats/{chat_id}/attachments",
|
||||
tags=["attachments"]
|
||||
)
|
||||
|
||||
router_download = APIRouter(
|
||||
prefix="/api/v1/attachments",
|
||||
tags=["attachments"]
|
||||
)
|
||||
|
||||
MAX_SIZE = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
MAX_ACTIVE_ATTACHMENTS = 100
|
||||
ADMISSION_LOCK_KEY = 823164001
|
||||
|
||||
def format_utc_timestamp(value: datetime | None) -> str:
|
||||
if value is None:
|
||||
value = datetime.now(timezone.utc)
|
||||
|
||||
elif value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
|
||||
return (
|
||||
value.astimezone(timezone.utc)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z")
|
||||
)
|
||||
|
||||
|
||||
def build_attachment_response(att: Attachment) -> dict:
|
||||
variants = []
|
||||
|
||||
if (
|
||||
att.status == "ready"
|
||||
and att.thumbnail_key
|
||||
and att.thumbnail_sha256
|
||||
and att.thumbnail_size_bytes is not None
|
||||
and att.thumbnail_width is not None
|
||||
and att.thumbnail_height is not None
|
||||
):
|
||||
variants.append({
|
||||
"name": "thumbnail",
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": att.thumbnail_size_bytes,
|
||||
"width": att.thumbnail_width,
|
||||
"height": att.thumbnail_height,
|
||||
"sha256": att.thumbnail_sha256,
|
||||
})
|
||||
|
||||
return {
|
||||
"id": str(att.id),
|
||||
"chat_id": str(att.chat_id),
|
||||
"owner_id": str(att.user_id),
|
||||
"filename": att.filename,
|
||||
"content_type": att.mime_type,
|
||||
"size_bytes": att.size_bytes,
|
||||
"sha256": att.sha256,
|
||||
"status": att.status,
|
||||
"variants": variants,
|
||||
"error_code": att.error_code,
|
||||
"created_at": format_utc_timestamp(att.created_at),
|
||||
"updated_at": format_utc_timestamp(att.updated_at),
|
||||
}
|
||||
|
||||
|
||||
@router_upload.post("", status_code=202)
|
||||
async def upload_attachment(
|
||||
chat_id: uuid.UUID,
|
||||
filename: str = Query(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=255,
|
||||
pattern=r"^[^/\\\x00]+$"
|
||||
),
|
||||
request: Request = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
sha_hasher = hashlib.sha256()
|
||||
buffer = io.BytesIO()
|
||||
total = 0
|
||||
first_bytes = b""
|
||||
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
|
||||
total += len(chunk)
|
||||
|
||||
if total > MAX_SIZE:
|
||||
raise HTTPException(413, "File too large")
|
||||
|
||||
sha_hasher.update(chunk)
|
||||
buffer.write(chunk)
|
||||
|
||||
if len(first_bytes) < 262:
|
||||
need = 262 - len(first_bytes)
|
||||
first_bytes += chunk[:need]
|
||||
|
||||
kind = filetype.guess(first_bytes)
|
||||
|
||||
if not kind or kind.mime not in ("image/png", "image/jpeg"):
|
||||
raise HTTPException(400, "Only PNG/JPEG allowed")
|
||||
|
||||
contents = buffer.getvalue()
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(contents))
|
||||
|
||||
if img.width * img.height > MAX_PIXELS:
|
||||
raise HTTPException(400, "Image too large (pixels)")
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(400, "Corrupted image")
|
||||
|
||||
# Serialize admission checks across all API instances.
|
||||
# This transaction-level PostgreSQL lock is released on commit/rollback.
|
||||
await session.execute(
|
||||
text("SELECT pg_advisory_xact_lock(:lock_key)"),
|
||||
{"lock_key": ADMISSION_LOCK_KEY},
|
||||
)
|
||||
|
||||
active_count = await session.scalar(
|
||||
select(func.count())
|
||||
.select_from(Attachment)
|
||||
.where(Attachment.status.in_(("queued", "processing")))
|
||||
)
|
||||
|
||||
if active_count >= MAX_ACTIVE_ATTACHMENTS:
|
||||
await session.rollback()
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="Image processing queue is full; try again later",
|
||||
headers={"Retry-After": "30"},
|
||||
)
|
||||
|
||||
object_key = f"{uuid.uuid4()}.{kind.extension}"
|
||||
|
||||
minio_client.put_object(
|
||||
BUCKET,
|
||||
object_key,
|
||||
io.BytesIO(contents),
|
||||
len(contents),
|
||||
content_type=kind.mime,
|
||||
)
|
||||
|
||||
sha_hash = sha_hasher.hexdigest()
|
||||
|
||||
att = Attachment(
|
||||
object_key=object_key,
|
||||
filename=filename,
|
||||
mime_type=kind.mime,
|
||||
size_bytes=len(contents),
|
||||
chat_id=chat_id,
|
||||
user_id=user.id,
|
||||
sha256=sha_hash,
|
||||
status="queued"
|
||||
)
|
||||
|
||||
session.add(att)
|
||||
await session.flush()
|
||||
|
||||
event = OutboxEvent(attachment_id=att.id)
|
||||
session.add(event)
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(att)
|
||||
|
||||
return build_attachment_response(att)
|
||||
|
||||
|
||||
@router_download.get("/{attachment_id}/content")
|
||||
async def download_attachment_content(
|
||||
attachment_id: uuid.UUID,
|
||||
variant: str = "original",
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
att = await session.get(Attachment, attachment_id)
|
||||
|
||||
if not att:
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == att.chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
if att.status != "ready":
|
||||
raise HTTPException(409, "File is not ready yet")
|
||||
|
||||
if variant == "thumbnail":
|
||||
if not att.thumbnail_key:
|
||||
raise HTTPException(404, "Thumbnail not found")
|
||||
|
||||
key_to_download = att.thumbnail_key
|
||||
mime = "image/jpeg"
|
||||
|
||||
elif variant == "original":
|
||||
key_to_download = att.object_key
|
||||
mime = att.mime_type
|
||||
|
||||
else:
|
||||
raise HTTPException(404, "Variant not found")
|
||||
|
||||
try:
|
||||
response = minio_client.get_object(
|
||||
BUCKET,
|
||||
key_to_download
|
||||
)
|
||||
|
||||
return StreamingResponse(
|
||||
response,
|
||||
media_type=mime,
|
||||
headers={
|
||||
"Content-Disposition":
|
||||
f'attachment; filename="{att.filename}"'
|
||||
},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
404,
|
||||
"File not found in storage"
|
||||
)
|
||||
|
||||
|
||||
@router_download.get("/{attachment_id}")
|
||||
async def get_attachment_metadata(
|
||||
attachment_id: uuid.UUID,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
att = await session.get(Attachment, attachment_id)
|
||||
|
||||
if not att:
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(
|
||||
ChatMember.chat_id == att.chat_id,
|
||||
ChatMember.user_id == user.id,
|
||||
)
|
||||
)
|
||||
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(404, "Not found")
|
||||
|
||||
return build_attachment_response(att)
|
||||
@@ -0,0 +1,83 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
|
||||
from pydantic import BaseModel, ConfigDict, field_serializer
|
||||
from app.redis_client import redis_client
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app.database import async_session_maker
|
||||
from app.models.user import User
|
||||
from app.security import verify_password, create_session, delete_session, bearer_scheme
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
security = HTTPBasic(realm="messenger")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: UserResponse
|
||||
|
||||
@field_serializer('expires_at')
|
||||
def serialize_dt(self, dt_str: str):
|
||||
if dt_str and dt_str.endswith("+00:00"):
|
||||
return dt_str.replace("+00:00", "Z")
|
||||
return dt_str
|
||||
|
||||
|
||||
# Basic Auth в Bearer Token
|
||||
@router.post("/sessions", status_code=201, response_model=SessionResponse)
|
||||
async def login(credentials: HTTPBasicCredentials = Depends(security)):
|
||||
async with async_session_maker() as session:
|
||||
result = await session.execute(select(User).where(User.username == credentials.username))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user or not verify_password(credentials.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
|
||||
session_data = await create_session(user.id)
|
||||
|
||||
session_data["user"] = user
|
||||
|
||||
return session_data
|
||||
|
||||
@router.delete("/sessions/current", status_code=204)
|
||||
async def logout(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
user_id = await redis_client.get(f"session:{token}")
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
await delete_session(token)
|
||||
return None
|
||||
@@ -0,0 +1,139 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
from app.pagination import paginate
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, v):
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("member_ids должны быть уникальными")
|
||||
return v
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: list[uuid.UUID]
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_chat(
|
||||
payload: CreateChat,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if str(user.id) not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="Пользователь должен быть участником чата")
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
result = await session.execute(select(User).where(User.id == member_id))
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=400, detail=f"несуществующий пользователь: {member_id}")
|
||||
|
||||
chat = Chat(title=payload.title)
|
||||
session.add(chat)
|
||||
await session.flush()
|
||||
|
||||
for member_id in payload.member_ids:
|
||||
session.add(ChatMember(chat_id=chat.id, user_id=member_id))
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(chat)
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": payload.member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{chat_id}")
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
result = await session.execute(select(Chat).where(Chat.id == chat_id))
|
||||
chat = result.scalar_one_or_none()
|
||||
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user.id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
return {
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_chats(
|
||||
limit: int = 20,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
result = await session.execute(
|
||||
select(Chat)
|
||||
.join(ChatMember, Chat.id == ChatMember.chat_id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
)
|
||||
chats = result.scalars().all()
|
||||
|
||||
my_chats = []
|
||||
for chat in chats:
|
||||
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||
member_ids = []
|
||||
for row in result.all():
|
||||
user_id = row[0]
|
||||
member_ids.append(str(user_id))
|
||||
|
||||
my_chats.append({
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||
})
|
||||
|
||||
page, next_cursor = paginate(my_chats, limit, cursor)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,34 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import text
|
||||
from app.database import async_session_maker
|
||||
from app.redis_client import redis_client
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def ready():
|
||||
try:
|
||||
async with async_session_maker() as session:
|
||||
await session.execute(text("SELECT 1"))
|
||||
|
||||
await redis_client.ping()
|
||||
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
@router.get("/")
|
||||
def home():
|
||||
return {
|
||||
"service": "MTUSI Messenger",
|
||||
"version": "1.1.0",
|
||||
"docs": "/docs",
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer, model_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from app.redis_client import redis_client
|
||||
import json
|
||||
|
||||
from app.models.message import Message
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.models.user import User
|
||||
from app.models.attachment import Attachment
|
||||
from app.security import get_current_user
|
||||
from app.dependencies import get_session
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=0, max_length=4000)
|
||||
attachment_ids: list[uuid.UUID] = []
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_text_or_attachment(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("Сообщение должно содержать текст или вложение")
|
||||
return self
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
attachment_ids: list[uuid.UUID] = []
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession):
|
||||
chat = await session.get(Chat, chat_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
|
||||
result = await session.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id)
|
||||
)
|
||||
if not result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail="чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=MessageResponse)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
payload: CreateMessage,
|
||||
idempotency_key: str = Header(
|
||||
...,
|
||||
alias="Idempotency-Key",
|
||||
min_length=1,
|
||||
max_length=128,
|
||||
pattern=r"^[A-Za-z0-9._:-]+$",
|
||||
),
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
if payload.attachment_ids:
|
||||
result = await session.execute(
|
||||
select(Attachment.id).where(
|
||||
Attachment.id.in_(payload.attachment_ids),
|
||||
Attachment.chat_id == chat_id,
|
||||
)
|
||||
)
|
||||
found_ids = {str(row[0]) for row in result.all()}
|
||||
requested_ids = {str(a) for a in payload.attachment_ids}
|
||||
if found_ids != requested_ids:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="attachment_ids содержат файлы из другого чата или несуществующие"
|
||||
)
|
||||
|
||||
redis_key = f"idem:{user.id}:{chat_id}:{idempotency_key}"
|
||||
body = payload.model_dump(mode="json")
|
||||
|
||||
raw = await redis_client.get(redis_key)
|
||||
if raw:
|
||||
stored = json.loads(raw)
|
||||
if stored["state"] == "done":
|
||||
if stored["request_body"] == body:
|
||||
return stored["response"]
|
||||
raise HTTPException(status_code=409, detail="Idempotency-Key переиспользован с другим телом запроса")
|
||||
raise HTTPException(status_code=409, detail="Запрос с этим Idempotency-Key ещё обрабатывается")
|
||||
|
||||
acquired = await redis_client.set(
|
||||
redis_key,
|
||||
json.dumps({"state": "processing", "request_body": body}),
|
||||
nx=True,
|
||||
ex=86400,
|
||||
)
|
||||
if not acquired:
|
||||
raise HTTPException(409, "Одновременный запрос с тем же самым Idempotency-Key")
|
||||
|
||||
message = Message(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=payload.text,
|
||||
attachment_ids=[str(a) for a in payload.attachment_ids]
|
||||
)
|
||||
session.add(message)
|
||||
await session.commit()
|
||||
await session.refresh(message)
|
||||
|
||||
response_data = {
|
||||
"id": str(message.id),
|
||||
"chat_id": str(message.chat_id),
|
||||
"sender_id": str(message.sender_id),
|
||||
"text": message.text,
|
||||
"created_at": message.created_at.isoformat().replace("+00:00", "Z"),
|
||||
"attachment_ids": message.attachment_ids,
|
||||
}
|
||||
|
||||
await redis_client.set(
|
||||
redis_key,
|
||||
json.dumps({"state": "done",
|
||||
"request_body": body,
|
||||
"response": response_data}),
|
||||
ex=86400,
|
||||
)
|
||||
|
||||
return response_data
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||
|
||||
await check_chat_access(chat_id, user.id, session)
|
||||
|
||||
offset = int(cursor) if cursor else 0
|
||||
|
||||
result = await session.execute(
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
.offset(offset)
|
||||
)
|
||||
msgs = result.scalars().all()
|
||||
|
||||
has_next = len(msgs) > limit
|
||||
if has_next:
|
||||
msgs = msgs[:limit]
|
||||
|
||||
my_messages = [
|
||||
{
|
||||
"id": m.id,
|
||||
"chat_id": m.chat_id,
|
||||
"sender_id": m.sender_id,
|
||||
"text": m.text,
|
||||
"created_at": m.created_at.isoformat().replace("+00:00", "Z"),
|
||||
"attachment_ids": m.attachment_ids,
|
||||
} for m in msgs
|
||||
]
|
||||
|
||||
next_cursor = str(offset + limit) if has_next else None
|
||||
return {"items": my_messages, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,55 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from app.models.user import User
|
||||
from app.security import get_password_hash, get_current_user
|
||||
from app.dependencies import get_session
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=5, max_length=128)
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer('created_at')
|
||||
def serialize_dt(self, dt: datetime):
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
@router.post("", status_code=201, response_model=UserResponse)
|
||||
async def register_user(payload: CreateUser, session: AsyncSession = Depends(get_session)):
|
||||
result = await session.execute(select(User).where(User.username == payload.username))
|
||||
if result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||
|
||||
user = User(
|
||||
username=payload.username,
|
||||
display_name=payload.display_name,
|
||||
password_hash=get_password_hash(payload.password)
|
||||
)
|
||||
session.add(user)
|
||||
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
await session.rollback()
|
||||
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||
|
||||
await session.refresh(user)
|
||||
return user
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
async def current_user(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,81 @@
|
||||
import secrets
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy import select
|
||||
from app.database import async_session_maker
|
||||
from app.models.user import User
|
||||
from app.redis_client import redis_client
|
||||
from app.config import SESSION_TTL_SECONDS
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
async def create_session(user_id: str) -> dict:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
|
||||
await redis_client.setex(
|
||||
name=f"session:{token}",
|
||||
time=SESSION_TTL_SECONDS,
|
||||
value=str(user_id),
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
async def delete_session(token: str) -> None:
|
||||
await redis_client.delete(f"session:{token}")
|
||||
|
||||
|
||||
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
|
||||
try:
|
||||
user_id = await redis_client.get(f"session:{token}")
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Внутренняя ошибка сервера"
|
||||
)
|
||||
|
||||
if not user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
async with async_session_maker() as session:
|
||||
result = await session.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
return user
|
||||
@@ -0,0 +1,22 @@
|
||||
import threading
|
||||
from minio import Minio
|
||||
from app.config import S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET
|
||||
|
||||
users_lock = threading.Lock()
|
||||
messages_lock = threading.Lock()
|
||||
|
||||
users_by_id: dict[str, dict] = {}
|
||||
users_by_username: dict[str, dict] = {}
|
||||
chats_by_id: dict[str, dict] = {}
|
||||
messages_by_chat: dict[str, list[dict]] = {}
|
||||
|
||||
endpoint = S3_ENDPOINT.replace("http://", "").replace("https://", "")
|
||||
|
||||
minio_client = Minio(
|
||||
endpoint,
|
||||
access_key=S3_ACCESS_KEY_ID,
|
||||
secret_key=S3_SECRET_ACCESS_KEY,
|
||||
secure=False,
|
||||
)
|
||||
|
||||
BUCKET = S3_BUCKET
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import aio_pika
|
||||
from minio import Minio
|
||||
from PIL import Image
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.user import User
|
||||
from app.models.chat import Chat, ChatMember
|
||||
from app.config import (
|
||||
DATABASE_URL,
|
||||
S3_ENDPOINT,
|
||||
S3_ACCESS_KEY_ID,
|
||||
S3_SECRET_ACCESS_KEY,
|
||||
S3_BUCKET,
|
||||
)
|
||||
|
||||
RABBITMQ_URL = os.getenv(
|
||||
"RABBITMQ_URL",
|
||||
"amqp://guest:guest@rabbitmq:5672/",
|
||||
)
|
||||
|
||||
QUEUE_NAME = "image_tasks"
|
||||
|
||||
MAX_ATTEMPTS = max(
|
||||
1, int(os.getenv("WORKER_MAX_ATTEMPTS", "5"))
|
||||
)
|
||||
|
||||
CONCURRENCY = max(
|
||||
1, int(os.getenv("WORKER_CONCURRENCY", "1"))
|
||||
)
|
||||
|
||||
PREFETCH = max(
|
||||
1, int(os.getenv("WORKER_PREFETCH", "1"))
|
||||
)
|
||||
|
||||
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
||||
PROCESS_TIMEOUT_SECONDS = 30
|
||||
LEASE_SECONDS = 300
|
||||
|
||||
endpoint = S3_ENDPOINT.replace(
|
||||
"http://", ""
|
||||
).replace(
|
||||
"https://", ""
|
||||
)
|
||||
|
||||
minio_client = Minio(
|
||||
endpoint,
|
||||
access_key=S3_ACCESS_KEY_ID,
|
||||
secret_key=S3_SECRET_ACCESS_KEY,
|
||||
secure=False,
|
||||
)
|
||||
|
||||
engine = create_async_engine(DATABASE_URL)
|
||||
|
||||
async_session_maker = async_sessionmaker(
|
||||
engine,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
class RetryableProcessingError(Exception):
|
||||
def __init__(self, error_code: str):
|
||||
self.error_code = error_code
|
||||
super().__init__(error_code)
|
||||
|
||||
|
||||
class PermanentProcessingError(Exception):
|
||||
def __init__(self, error_code: str):
|
||||
self.error_code = error_code
|
||||
super().__init__(error_code)
|
||||
|
||||
|
||||
class LeaseBusyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class LeaseLostError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def get_rss_mb():
|
||||
try:
|
||||
with open("/proc/self/status") as file:
|
||||
for line in file:
|
||||
if line.startswith("VmRSS:"):
|
||||
kb = int(line.split()[1])
|
||||
return round(kb / 1024, 2)
|
||||
except (OSError, ValueError, IndexError):
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def claim_attachment(attachment_id: str):
|
||||
async with async_session_maker() as session:
|
||||
async with session.begin():
|
||||
att = await session.get(
|
||||
Attachment,
|
||||
uuid.UUID(attachment_id),
|
||||
with_for_update=True,
|
||||
)
|
||||
|
||||
if att is None:
|
||||
print(
|
||||
f"[Worker] Файл {attachment_id} не найден",
|
||||
flush=True,
|
||||
)
|
||||
return None
|
||||
|
||||
if att.status == "ready" and att.thumbnail_key:
|
||||
print(
|
||||
f"[Worker] Файл {attachment_id} уже обработан",
|
||||
flush=True,
|
||||
)
|
||||
return None
|
||||
|
||||
if att.status == "failed":
|
||||
print(
|
||||
f"[Worker] Файл {attachment_id} уже failed",
|
||||
flush=True,
|
||||
)
|
||||
return None
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
if (
|
||||
att.status == "processing"
|
||||
and att.lease_expires_at is not None
|
||||
and att.lease_expires_at > now
|
||||
):
|
||||
raise LeaseBusyError()
|
||||
|
||||
lease_expires_at = now + timedelta(
|
||||
seconds=LEASE_SECONDS
|
||||
)
|
||||
|
||||
att.status = "processing"
|
||||
att.error_code = None
|
||||
att.lease_expires_at = lease_expires_at
|
||||
|
||||
object_key = att.object_key
|
||||
|
||||
return object_key, lease_expires_at
|
||||
|
||||
|
||||
async def release_lease(
|
||||
attachment_id: str,
|
||||
lease_expires_at: datetime,
|
||||
):
|
||||
async with async_session_maker() as session:
|
||||
async with session.begin():
|
||||
att = await session.get(
|
||||
Attachment,
|
||||
uuid.UUID(attachment_id),
|
||||
with_for_update=True,
|
||||
)
|
||||
|
||||
if (
|
||||
att is not None
|
||||
and att.status == "processing"
|
||||
and att.lease_expires_at == lease_expires_at
|
||||
):
|
||||
att.status = "queued"
|
||||
att.lease_expires_at = None
|
||||
|
||||
|
||||
async def mark_failed(
|
||||
attachment_id: str,
|
||||
error_code: str,
|
||||
):
|
||||
async with async_session_maker() as session:
|
||||
async with session.begin():
|
||||
att = await session.get(
|
||||
Attachment,
|
||||
uuid.UUID(attachment_id),
|
||||
with_for_update=True,
|
||||
)
|
||||
|
||||
if att is None or att.status == "ready":
|
||||
return
|
||||
|
||||
if att.status == "processing":
|
||||
raise LeaseBusyError()
|
||||
|
||||
att.status = "failed"
|
||||
att.error_code = error_code
|
||||
att.lease_expires_at = None
|
||||
|
||||
print(
|
||||
f"[Worker] Файл {attachment_id}: "
|
||||
f"failed, error_code={error_code}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
async def process_image(image_data: bytes):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
directory = Path(temp_dir)
|
||||
|
||||
input_path = directory / "original"
|
||||
input_path.write_bytes(image_data)
|
||||
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-m",
|
||||
"app.image_processor",
|
||||
str(input_path),
|
||||
str(directory),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
except OSError as exc:
|
||||
raise RetryableProcessingError(
|
||||
"image_processor_start_error"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
process.communicate(),
|
||||
timeout=PROCESS_TIMEOUT_SECONDS,
|
||||
)
|
||||
except asyncio.TimeoutError as exc:
|
||||
if process.returncode is None:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
await process.communicate()
|
||||
|
||||
raise RetryableProcessingError(
|
||||
"image_processing_timeout"
|
||||
) from exc
|
||||
|
||||
if process.returncode == 20:
|
||||
raise PermanentProcessingError(
|
||||
"image_too_many_pixels"
|
||||
)
|
||||
|
||||
if process.returncode == 21:
|
||||
raise PermanentProcessingError(
|
||||
"image_processing_error"
|
||||
)
|
||||
|
||||
if process.returncode != 0:
|
||||
raise RetryableProcessingError(
|
||||
"image_processor_error"
|
||||
)
|
||||
|
||||
try:
|
||||
thumb_bytes = (
|
||||
directory / "thumbnail.jpg"
|
||||
).read_bytes()
|
||||
|
||||
crop_bytes = (
|
||||
directory / "crop.jpg"
|
||||
).read_bytes()
|
||||
|
||||
webp_bytes = (
|
||||
directory / "optimized.webp"
|
||||
).read_bytes()
|
||||
|
||||
with Image.open(
|
||||
io.BytesIO(thumb_bytes)
|
||||
) as thumbnail:
|
||||
thumb_width, thumb_height = thumbnail.size
|
||||
|
||||
except OSError as exc:
|
||||
raise RetryableProcessingError(
|
||||
"image_processor_output_error"
|
||||
) from exc
|
||||
|
||||
return (
|
||||
thumb_bytes,
|
||||
crop_bytes,
|
||||
webp_bytes,
|
||||
thumb_width,
|
||||
thumb_height,
|
||||
)
|
||||
|
||||
|
||||
async def process_attachment(attachment_id: str):
|
||||
print(
|
||||
f"[Worker] Обработка файла: {attachment_id}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
claim = await claim_attachment(attachment_id)
|
||||
|
||||
if claim is None:
|
||||
return
|
||||
|
||||
object_key, lease_expires_at = claim
|
||||
|
||||
try:
|
||||
try:
|
||||
response = minio_client.get_object(
|
||||
S3_BUCKET,
|
||||
object_key,
|
||||
)
|
||||
|
||||
try:
|
||||
image_data = response.read(
|
||||
MAX_IMAGE_BYTES + 1
|
||||
)
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
except Exception as exc:
|
||||
raise RetryableProcessingError(
|
||||
"s3_download_error"
|
||||
) from exc
|
||||
|
||||
if len(image_data) > MAX_IMAGE_BYTES:
|
||||
raise PermanentProcessingError(
|
||||
"image_too_large"
|
||||
)
|
||||
|
||||
(
|
||||
thumb_bytes,
|
||||
crop_bytes,
|
||||
webp_bytes,
|
||||
thumb_width,
|
||||
thumb_height,
|
||||
) = await process_image(image_data)
|
||||
|
||||
thumb_key = f"thumbnails/{object_key}"
|
||||
crop_key = f"crops/{attachment_id}.jpg"
|
||||
webp_key = f"webp/{attachment_id}.webp"
|
||||
|
||||
try:
|
||||
minio_client.put_object(
|
||||
S3_BUCKET,
|
||||
thumb_key,
|
||||
io.BytesIO(thumb_bytes),
|
||||
len(thumb_bytes),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
|
||||
minio_client.put_object(
|
||||
S3_BUCKET,
|
||||
crop_key,
|
||||
io.BytesIO(crop_bytes),
|
||||
len(crop_bytes),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
|
||||
minio_client.put_object(
|
||||
S3_BUCKET,
|
||||
webp_key,
|
||||
io.BytesIO(webp_bytes),
|
||||
len(webp_bytes),
|
||||
content_type="image/webp",
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
raise RetryableProcessingError(
|
||||
"s3_upload_error"
|
||||
) from exc
|
||||
|
||||
async with async_session_maker() as session:
|
||||
async with session.begin():
|
||||
att = await session.get(
|
||||
Attachment,
|
||||
uuid.UUID(attachment_id),
|
||||
with_for_update=True,
|
||||
)
|
||||
|
||||
if (
|
||||
att is None
|
||||
or att.status != "processing"
|
||||
or att.lease_expires_at != lease_expires_at
|
||||
):
|
||||
raise LeaseLostError()
|
||||
|
||||
att.thumbnail_key = thumb_key
|
||||
att.thumbnail_sha256 = hashlib.sha256(
|
||||
thumb_bytes
|
||||
).hexdigest()
|
||||
att.thumbnail_size_bytes = len(thumb_bytes)
|
||||
att.thumbnail_width = thumb_width
|
||||
att.thumbnail_height = thumb_height
|
||||
att.crop_key = crop_key
|
||||
att.webp_key = webp_key
|
||||
att.status = "ready"
|
||||
att.error_code = None
|
||||
att.lease_expires_at = None
|
||||
|
||||
print(
|
||||
f"[Worker] Успешно обработан {attachment_id}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
except Exception:
|
||||
await release_lease(
|
||||
attachment_id,
|
||||
lease_expires_at,
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
async def main():
|
||||
connection = await aio_pika.connect_robust(
|
||||
RABBITMQ_URL
|
||||
)
|
||||
|
||||
async with connection:
|
||||
channel = await connection.channel(
|
||||
publisher_confirms=True
|
||||
)
|
||||
|
||||
await channel.set_qos(
|
||||
prefetch_count=PREFETCH
|
||||
)
|
||||
|
||||
queue = await channel.declare_queue(
|
||||
QUEUE_NAME,
|
||||
durable=True,
|
||||
)
|
||||
|
||||
semaphore = asyncio.Semaphore(CONCURRENCY)
|
||||
|
||||
print(
|
||||
f"[Worker] CONCURRENCY={CONCURRENCY}, "
|
||||
f"PREFETCH={PREFETCH}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
async def on_message(
|
||||
message: aio_pika.IncomingMessage
|
||||
):
|
||||
async with semaphore:
|
||||
started = time.perf_counter()
|
||||
|
||||
try:
|
||||
data = json.loads(
|
||||
message.body.decode()
|
||||
)
|
||||
|
||||
attachment_id = str(
|
||||
uuid.UUID(data["attachment_id"])
|
||||
)
|
||||
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
):
|
||||
print(
|
||||
"[Worker] Некорректное сообщение",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await message.reject(
|
||||
requeue=False
|
||||
)
|
||||
return
|
||||
|
||||
headers = dict(message.headers or {})
|
||||
|
||||
try:
|
||||
attempt = max(
|
||||
1,
|
||||
int(headers.get("x-attempt", 1)),
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
attempt = 1
|
||||
|
||||
print(
|
||||
f"[Worker] Попытка "
|
||||
f"{attempt}/{MAX_ATTEMPTS} "
|
||||
f"для {attachment_id}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
try:
|
||||
await process_attachment(
|
||||
attachment_id
|
||||
)
|
||||
|
||||
except LeaseBusyError:
|
||||
print(
|
||||
"[Worker] Задание уже "
|
||||
"обрабатывается, ждём Lease",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await asyncio.sleep(5)
|
||||
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
return
|
||||
|
||||
except LeaseLostError:
|
||||
print(
|
||||
"[Worker] Lease перешёл "
|
||||
"другому Worker",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await message.ack()
|
||||
return
|
||||
|
||||
except PermanentProcessingError as exc:
|
||||
try:
|
||||
await mark_failed(
|
||||
attachment_id,
|
||||
exc.error_code,
|
||||
)
|
||||
except Exception:
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
return
|
||||
|
||||
except Exception as exc:
|
||||
error_code = (
|
||||
exc.error_code
|
||||
if isinstance(
|
||||
exc,
|
||||
RetryableProcessingError,
|
||||
)
|
||||
else "worker_error"
|
||||
)
|
||||
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
next_attempt = attempt + 1
|
||||
|
||||
print(
|
||||
f"[Worker] Ошибка {error_code}. "
|
||||
f"Повтор "
|
||||
f"{next_attempt}/{MAX_ATTEMPTS}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
headers["x-attempt"] = next_attempt
|
||||
|
||||
base_delay = min(
|
||||
30,
|
||||
2 ** (attempt - 1),
|
||||
)
|
||||
|
||||
delay = base_delay + random.uniform(
|
||||
0,
|
||||
base_delay / 2,
|
||||
)
|
||||
|
||||
print(
|
||||
f"[Worker] Повтор через "
|
||||
f"{delay:.1f} сек.",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await asyncio.sleep(delay)
|
||||
|
||||
try:
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=message.body,
|
||||
headers=headers,
|
||||
delivery_mode=(
|
||||
aio_pika.DeliveryMode.PERSISTENT
|
||||
),
|
||||
content_type="application/json",
|
||||
),
|
||||
routing_key=QUEUE_NAME,
|
||||
)
|
||||
|
||||
except Exception:
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
return
|
||||
|
||||
print(
|
||||
f"[Worker] Попытки исчерпаны: "
|
||||
f"{attachment_id}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
try:
|
||||
await mark_failed(
|
||||
attachment_id,
|
||||
error_code,
|
||||
)
|
||||
except Exception:
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
|
||||
duration = time.perf_counter() - started
|
||||
rss_mb = get_rss_mb()
|
||||
|
||||
print(
|
||||
f"[Metrics] attachment_id={attachment_id} "
|
||||
f"duration_s={duration:.3f} "
|
||||
f"rss_mb={rss_mb}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
print(
|
||||
"[Worker] Ждем сообщения из RabbitMQ...",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await queue.consume(on_message)
|
||||
await asyncio.Future()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user