ЛР 7: безопасность, mTLS и OpenBao на оценку 3
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
+47
@@ -0,0 +1,47 @@
|
||||
"""Load only this service's settings from OpenBao before starting it."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
CA_FILE = "/run/ca/ca.crt"
|
||||
|
||||
|
||||
def request(address, path, *, context, data=None, token=None):
|
||||
if not address.startswith("https://"):
|
||||
raise ValueError("OpenBao requires HTTPS")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = urllib.request.Request(
|
||||
address + "/v1/" + path,
|
||||
headers=headers,
|
||||
data=json.dumps(data).encode() if data is not None else None,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=context, timeout=8) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else None
|
||||
|
||||
|
||||
def service_token(address, context, identity=Path("/run/identity")):
|
||||
role = {name: (identity / name).read_text().strip() for name in ("role_id", "secret_id")}
|
||||
return request(address, "auth/approle/login", context=context, data=role)["auth"]["client_token"]
|
||||
|
||||
|
||||
def main():
|
||||
address = os.environ["BAO_ADDR"]
|
||||
role = os.environ["BAO_ROLE"]
|
||||
context = ssl.create_default_context(cafile=CA_FILE)
|
||||
try:
|
||||
token = service_token(address, context)
|
||||
values = request(address, f"messenger/data/{role}", context=context, token=token)["data"]["data"]
|
||||
request(address, "auth/token/revoke-self", context=context, data={}, token=token)
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
raise SystemExit(f"OpenBao bootstrap failed ({type(error).__name__})") from None
|
||||
os.execvpe(sys.argv[1], sys.argv[1:], {**os.environ, **values})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,25 @@
|
||||
import os
|
||||
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
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")
|
||||
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY")
|
||||
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
@@ -0,0 +1,17 @@
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.config import DATABASE_URL
|
||||
from app.transport import database_tls
|
||||
|
||||
engine = create_async_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800,
|
||||
echo=False,
|
||||
hide_parameters=True,
|
||||
connect_args=database_tls(),
|
||||
)
|
||||
|
||||
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())
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi import HTTPException
|
||||
import uuid
|
||||
import time
|
||||
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
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
|
||||
from app.telemetry import setup_telemetry
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.1.0",
|
||||
)
|
||||
|
||||
tracer_provider, meter_provider, logger_provider, logger = setup_telemetry(
|
||||
"messenger-api"
|
||||
)
|
||||
|
||||
tracer = tracer_provider.get_tracer(__name__)
|
||||
meter = meter_provider.get_meter(__name__)
|
||||
|
||||
http_requests = meter.create_counter(
|
||||
name="http_requests",
|
||||
description="Total HTTP requests",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
http_duration = meter.create_histogram(
|
||||
name="http_request_duration",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
|
||||
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.middleware("http")
|
||||
async def telemetry_middleware(request, call_next):
|
||||
start_time = time.perf_counter()
|
||||
method = request.method
|
||||
status_code = 500
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
method,
|
||||
kind=SpanKind.SERVER,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
return response
|
||||
|
||||
finally:
|
||||
duration = time.perf_counter() - start_time
|
||||
|
||||
route = request.scope.get("route")
|
||||
route_template = getattr(route, "path", "unknown")
|
||||
|
||||
attributes = {
|
||||
"method": method,
|
||||
"route": route_template,
|
||||
"status_class": f"{status_code // 100}xx",
|
||||
}
|
||||
|
||||
http_requests.add(1, attributes)
|
||||
http_duration.record(duration, attributes)
|
||||
|
||||
span.update_name(f"{method} {route_template}")
|
||||
span.set_attribute("http.request.method", method)
|
||||
span.set_attribute("http.route", route_template)
|
||||
span.set_attribute(
|
||||
"http.response.status_code",
|
||||
status_code,
|
||||
)
|
||||
|
||||
if status_code >= 500:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
|
||||
logger.log(
|
||||
40 if status_code >= 500 else 20,
|
||||
"http_request_completed",
|
||||
extra={
|
||||
"event": "http_request_completed",
|
||||
"method": method,
|
||||
"route": route_template,
|
||||
"status_code": status_code,
|
||||
"duration_seconds": duration,
|
||||
"request_id": getattr(
|
||||
request.state,
|
||||
"request_id",
|
||||
"",
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
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,139 @@
|
||||
|
||||
import asyncio
|
||||
|
||||
from app.transport import database_tls, service_tls
|
||||
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.environ["RABBITMQ_URL"]
|
||||
QUEUE_NAME = "image_tasks"
|
||||
POLL_INTERVAL_SECONDS = 1
|
||||
|
||||
engine = create_async_engine(DATABASE_URL, connect_args=database_tls(), hide_parameters=True)
|
||||
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, ssl_context=service_tls())
|
||||
|
||||
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,12 @@
|
||||
import redis.asyncio as redis
|
||||
import os
|
||||
from app.config import REDIS_URL
|
||||
|
||||
redis_client = redis.from_url(
|
||||
REDIS_URL,
|
||||
decode_responses=True,
|
||||
socket_timeout=3,
|
||||
socket_connect_timeout=3,
|
||||
**({"ssl_ca_certs": os.environ["TLS_CA_FILE"], "ssl_check_hostname": True}
|
||||
if REDIS_URL.startswith("rediss://") else {}),
|
||||
)
|
||||
@@ -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,285 @@
|
||||
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"]
|
||||
)
|
||||
|
||||
from app.config import MAX_UPLOAD_BYTES as MAX_SIZE, MAX_IMAGE_PIXELS as MAX_PIXELS
|
||||
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"originals/{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,106 @@
|
||||
from base64 import b64decode
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
|
||||
from fastapi.security.utils import get_authorization_scheme_param
|
||||
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 check_password, create_session, delete_session, bearer_scheme, session_key
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
class Utf8Basic(HTTPBasic):
|
||||
async def __call__(self, request: Request) -> HTTPBasicCredentials:
|
||||
scheme, parameter = get_authorization_scheme_param(request.headers.get("Authorization"))
|
||||
if scheme.lower() == "basic":
|
||||
try:
|
||||
username, separator, password = b64decode(
|
||||
parameter, validate=True
|
||||
).decode("utf-8").partition(":")
|
||||
if separator:
|
||||
return HTTPBasicCredentials(username=username, password=password)
|
||||
except ValueError:
|
||||
pass
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid Basic credentials",
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||
)
|
||||
|
||||
|
||||
security = Utf8Basic(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 len(credentials.password) > 128 or not await check_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(session_key(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=await 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
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import secrets
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import asyncio
|
||||
import hashlib
|
||||
import bcrypt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError, InvalidHashError
|
||||
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 = PasswordHasher(
|
||||
memory_cost=19456, time_cost=2, parallelism=1,
|
||||
)
|
||||
password_slots = asyncio.Semaphore(2)
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
async def get_password_hash(password: str) -> str:
|
||||
async with password_slots:
|
||||
return await asyncio.to_thread(pwd_context.hash, password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
if hashed.startswith(("$2b$", "$2a$", "$2y$")):
|
||||
password = plain.encode()
|
||||
return len(password) <= 72 and bcrypt.checkpw(password, hashed.encode())
|
||||
return pwd_context.verify(hashed, plain)
|
||||
except (VerificationError, InvalidHashError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
async def check_password(plain: str, hashed: str) -> bool:
|
||||
async with password_slots:
|
||||
return await asyncio.to_thread(verify_password, plain, hashed)
|
||||
|
||||
|
||||
def session_key(token: str) -> str:
|
||||
return "session:" + hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
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=session_key(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(session_key(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(session_key(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,35 @@
|
||||
"""Require a verified certificate with the ingress identity before parsing HTTP."""
|
||||
import ssl
|
||||
|
||||
import uvicorn
|
||||
from uvicorn.protocols.http.h11_impl import H11Protocol
|
||||
|
||||
|
||||
class IngressOnlyProtocol(H11Protocol):
|
||||
def connection_made(self, transport):
|
||||
super().connection_made(transport)
|
||||
tls = transport.get_extra_info("ssl_object")
|
||||
if tls is None or ("URI", "spiffe://lab7/ingress") not in tls.getpeercert().get(
|
||||
"subjectAltName", ()
|
||||
):
|
||||
transport.close()
|
||||
return
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8443,
|
||||
http=IngressOnlyProtocol,
|
||||
proxy_headers=False,
|
||||
access_log=False,
|
||||
ssl_certfile="/run/identity/server.crt",
|
||||
ssl_keyfile="/run/identity/server.key",
|
||||
ssl_ca_certs="/run/ca/ca.crt",
|
||||
ssl_cert_reqs=ssl.CERT_REQUIRED,
|
||||
timeout_graceful_shutdown=5,
|
||||
)
|
||||
config.load()
|
||||
config.ssl.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
uvicorn.Server(config).run()
|
||||
@@ -0,0 +1,23 @@
|
||||
import threading
|
||||
from minio import Minio
|
||||
from app.transport import s3_transport
|
||||
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,
|
||||
**s3_transport(S3_ENDPOINT),
|
||||
)
|
||||
|
||||
BUCKET = S3_BUCKET
|
||||
@@ -0,0 +1,136 @@
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
|
||||
from opentelemetry.sdk.metrics.view import (
|
||||
View,
|
||||
ExplicitBucketHistogramAggregation,
|
||||
)
|
||||
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
|
||||
|
||||
def setup_telemetry(service_name):
|
||||
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318")
|
||||
username = os.environ.get("OTEL_USERNAME")
|
||||
options = {}
|
||||
if username:
|
||||
credential = f"{username}:{os.environ['OTEL_PASSWORD']}".encode()
|
||||
options = {
|
||||
"certificate_file": os.environ["TLS_CA_FILE"],
|
||||
"headers": {"Authorization": "Basic " + base64.b64encode(credential).decode()},
|
||||
"timeout": 5,
|
||||
}
|
||||
|
||||
resource = Resource.create({
|
||||
"service.name": service_name,
|
||||
"service.version": "1.1.0",
|
||||
"service.instance.id": socket.gethostname(),
|
||||
"deployment.environment.name": "lab",
|
||||
})
|
||||
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(
|
||||
endpoint=f"{endpoint}/v1/traces",
|
||||
**options,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
metric_reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(
|
||||
endpoint=f"{endpoint}/v1/metrics",
|
||||
**options,
|
||||
),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
|
||||
http_duration_view = View(
|
||||
instrument_name="http_request_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.005,
|
||||
0.01,
|
||||
0.025,
|
||||
0.05,
|
||||
0.1,
|
||||
0.25,
|
||||
0.5,
|
||||
1,
|
||||
2.5,
|
||||
5,
|
||||
10,
|
||||
30,
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
job_duration_view = View(
|
||||
instrument_name="job_processing_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.05,
|
||||
0.1,
|
||||
0.25,
|
||||
0.5,
|
||||
1,
|
||||
2.5,
|
||||
5,
|
||||
10,
|
||||
20,
|
||||
30,
|
||||
60,
|
||||
120,
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
meter_provider = MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[metric_reader],
|
||||
views=[
|
||||
http_duration_view,
|
||||
job_duration_view,
|
||||
],
|
||||
)
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(
|
||||
endpoint=f"{endpoint}/v1/logs",
|
||||
**options,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
logger = logging.getLogger(service_name)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
logger.addHandler(
|
||||
LoggingHandler(
|
||||
level=logging.INFO,
|
||||
logger_provider=logger_provider,
|
||||
)
|
||||
)
|
||||
|
||||
return tracer_provider, meter_provider, logger_provider, logger
|
||||
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
import ssl
|
||||
|
||||
import urllib3
|
||||
|
||||
|
||||
def service_tls():
|
||||
ca = os.getenv("TLS_CA_FILE")
|
||||
return ssl.create_default_context(cafile=ca) if ca else None
|
||||
|
||||
|
||||
def database_tls():
|
||||
context = service_tls()
|
||||
return {"ssl": context} if context else {}
|
||||
|
||||
|
||||
def s3_transport(endpoint):
|
||||
if not endpoint.startswith("https://"):
|
||||
return {"secure": False}
|
||||
return {
|
||||
"secure": True,
|
||||
"http_client": urllib3.PoolManager(
|
||||
ssl_context=ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"]),
|
||||
timeout=urllib3.Timeout(connect=5, read=10),
|
||||
),
|
||||
}
|
||||
+750
@@ -0,0 +1,750 @@
|
||||
import asyncio
|
||||
|
||||
from app.transport import database_tls, service_tls
|
||||
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 app.transport import s3_transport
|
||||
from PIL import Image
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from app.telemetry import setup_telemetry
|
||||
|
||||
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.environ["RABBITMQ_URL"]
|
||||
|
||||
|
||||
QUEUE_NAME = "image_tasks"
|
||||
|
||||
tracer_provider, meter_provider, logger_provider, logger = setup_telemetry(
|
||||
"messenger-worker"
|
||||
)
|
||||
|
||||
tracer = tracer_provider.get_tracer(__name__)
|
||||
meter = meter_provider.get_meter(__name__)
|
||||
|
||||
jobs_processed = meter.create_counter(
|
||||
name="jobs_processed",
|
||||
description="Total job processing attempts",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
job_processing_duration = meter.create_histogram(
|
||||
name="job_processing_duration",
|
||||
description="Job processing duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
**s3_transport(S3_ENDPOINT),
|
||||
)
|
||||
|
||||
|
||||
engine = create_async_engine(DATABASE_URL, connect_args=database_tls(), hide_parameters=True)
|
||||
|
||||
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 "skipped"
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
return "success"
|
||||
|
||||
except Exception:
|
||||
await release_lease(
|
||||
attachment_id,
|
||||
lease_expires_at,
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
async def main():
|
||||
connection = await aio_pika.connect_robust(
|
||||
RABBITMQ_URL, ssl_context=service_tls()
|
||||
)
|
||||
|
||||
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()
|
||||
|
||||
outcome = "failed"
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"image_tasks process",
|
||||
kind=SpanKind.CONSUMER,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
|
||||
span.set_attribute(
|
||||
"messaging.system", "rabbitmq"
|
||||
)
|
||||
span.set_attribute(
|
||||
"messaging.destination.name", QUEUE_NAME
|
||||
)
|
||||
|
||||
try:
|
||||
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:
|
||||
result = await process_attachment(
|
||||
attachment_id
|
||||
)
|
||||
|
||||
except LeaseBusyError:
|
||||
print(
|
||||
"[Worker] Задание уже "
|
||||
"обрабатывается, ждём Lease",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await asyncio.sleep(5)
|
||||
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
|
||||
outcome = "retry"
|
||||
return
|
||||
|
||||
except LeaseLostError:
|
||||
print(
|
||||
"[Worker] Lease перешёл "
|
||||
"другому Worker",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
await message.ack()
|
||||
|
||||
outcome = "skipped"
|
||||
return
|
||||
|
||||
except PermanentProcessingError as exc:
|
||||
try:
|
||||
await mark_failed(
|
||||
attachment_id,
|
||||
exc.error_code,
|
||||
)
|
||||
except Exception:
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
|
||||
outcome = "retry"
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
|
||||
outcome = "failed"
|
||||
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
|
||||
)
|
||||
|
||||
outcome = "retry"
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
|
||||
outcome = "retry"
|
||||
return
|
||||
|
||||
print(
|
||||
f"[Worker] Попытки исчерпаны: "
|
||||
f"{attachment_id}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
try:
|
||||
await mark_failed(
|
||||
attachment_id,
|
||||
error_code,
|
||||
)
|
||||
except Exception:
|
||||
await message.nack(
|
||||
requeue=True
|
||||
)
|
||||
|
||||
outcome = "retry"
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
|
||||
outcome = "failed"
|
||||
return
|
||||
|
||||
await message.ack()
|
||||
|
||||
outcome = result
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
finally:
|
||||
duration = time.perf_counter() - started
|
||||
|
||||
attributes = {
|
||||
"job_type": "image_processing",
|
||||
"outcome": outcome,
|
||||
}
|
||||
|
||||
jobs_processed.add(
|
||||
1,
|
||||
attributes,
|
||||
)
|
||||
|
||||
job_processing_duration.record(
|
||||
duration,
|
||||
attributes,
|
||||
)
|
||||
|
||||
span.set_attribute(
|
||||
"job.type",
|
||||
"image_processing",
|
||||
)
|
||||
|
||||
span.set_attribute(
|
||||
"job.outcome",
|
||||
outcome,
|
||||
)
|
||||
|
||||
if outcome in ("failed", "retry"):
|
||||
span.set_status(
|
||||
Status(StatusCode.ERROR)
|
||||
)
|
||||
|
||||
logger.log(
|
||||
40 if outcome == "failed"
|
||||
else 30 if outcome == "retry"
|
||||
else 20,
|
||||
"job_processing_completed",
|
||||
extra={
|
||||
"event": "job_processing_completed",
|
||||
"job_type": "image_processing",
|
||||
"outcome": outcome,
|
||||
"duration_seconds": duration,
|
||||
},
|
||||
)
|
||||
|
||||
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