Перенесла файлы проекта из предыдущей лабораторной работы
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
"""Вложения (lab5/lab6): upload → 202 queued, async worker, download вариантов.
|
||||
|
||||
lab6: при создании outbox-строки кладём в payload W3C traceparent/tracestate
|
||||
текущего HTTP-запроса. Ошибка инжекта не должна блокировать upload.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import unicodedata
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from botocore.exceptions import ClientError
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
PIPELINE_VERSION = 1
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _validate_filename(name: str) -> str:
|
||||
if not name or len(name) > 255:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if name.strip() != name or name.strip() == "":
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
for ch in name:
|
||||
if ch in ("/", "\\", "\x00") or unicodedata.category(ch).startswith("C"):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return name
|
||||
|
||||
|
||||
def _detect_content_type(data: bytes) -> Optional[str]:
|
||||
"""MIME по содержимому, не по заголовку."""
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> str:
|
||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования."""
|
||||
ctype = _detect_content_type(data)
|
||||
if ctype is None:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
width, height = img.size
|
||||
if width <= 0 or height <= 0:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
if width * height > MAX_IMAGE_PIXELS:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
img.load()
|
||||
except HTTPException:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
return ctype
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/chats/{chat_id}/attachments",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB (lab5: 202 queued)",
|
||||
response_model=Attachment,
|
||||
status_code=202,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
filename: str = Query(...),
|
||||
) -> Attachment:
|
||||
_require_member(chat_id, user.id)
|
||||
safe_name = _validate_filename(filename)
|
||||
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
if int(cl) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
chunks.append(chunk)
|
||||
body = b"".join(chunks)
|
||||
if not body:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
content_type = await run_in_threadpool(_validate_image, body)
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
|
||||
attachment_id = uuid4()
|
||||
staging_key = s3.staging_key(chat_id, attachment_id)
|
||||
|
||||
# 1) Durable staging в S3 (приватный prefix).
|
||||
try:
|
||||
await run_in_threadpool(s3.put_bytes, staging_key, body, content_type)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
att = Attachment(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user.id,
|
||||
filename=safe_name,
|
||||
content_type=content_type,
|
||||
size_bytes=len(body),
|
||||
sha256=sha256,
|
||||
status="queued",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
job_id = uuid4()
|
||||
|
||||
# lab6: снимок W3C trace context активного HTTP span.
|
||||
trace_carrier: dict[str, str] = {}
|
||||
try:
|
||||
_propagator.inject(trace_carrier)
|
||||
except Exception:
|
||||
trace_carrier = {}
|
||||
|
||||
outbox_payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": PIPELINE_VERSION,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
if trace_carrier.get("traceparent"):
|
||||
outbox_payload["traceparent"] = trace_carrier["traceparent"]
|
||||
if trace_carrier.get("tracestate"):
|
||||
outbox_payload["tracestate"] = trace_carrier["tracestate"]
|
||||
|
||||
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||
# При сбое — компенсация: удаляем staging.
|
||||
try:
|
||||
await run_in_threadpool(
|
||||
storage.create_attachment_queued, att, staging_key, outbox_payload
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await run_in_threadpool(s3.delete_object, staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
return att
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}",
|
||||
summary="Метаданные вложения, доступ участникам чата",
|
||||
response_model=Attachment,
|
||||
)
|
||||
def get_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
) -> Attachment:
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
att, _key = pair
|
||||
_require_member(att.chat_id, user.id)
|
||||
return att
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}/content",
|
||||
summary="Скачать байты (original или variant) через авторизованный API",
|
||||
)
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
variant: str = Query("original"),
|
||||
):
|
||||
if variant not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
att, object_key = pair
|
||||
_require_member(att.chat_id, user.id)
|
||||
if att.status != "ready":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
if variant == "original":
|
||||
key = object_key
|
||||
ctype_expected = att.content_type
|
||||
else:
|
||||
vs = [v for v in att.variants if v.name == variant]
|
||||
if not vs:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
v = vs[0]
|
||||
key = s3.variant_key(att.chat_id, att.id, variant)
|
||||
ctype_expected = v.content_type
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code in ("404", "NoSuchKey", "NotFound"):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=ctype or ctype_expected,
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
|
||||
from ..models.schemas import Session
|
||||
from ..storage.postgres import storage
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
DEFAULT_TTL_SECONDS = 3600
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
try:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", DEFAULT_TTL_SECONDS))
|
||||
except ValueError:
|
||||
return DEFAULT_TTL_SECONDS
|
||||
|
||||
|
||||
def _parse_basic_header(request: Request) -> tuple[str, str] | None:
|
||||
"""Ручной разбор Basic: base64 -> UTF-8 -> split по первому ':'.
|
||||
|
||||
HTTPBasic из Starlette декодирует latin-1 и ломает кириллицу.
|
||||
Здесь пароль читается как UTF-8 (RFC 7617 разрешает UTF-8 charset).
|
||||
Username остаётся ASCII по контракту.
|
||||
"""
|
||||
raw = request.headers.get("Authorization", "")
|
||||
if not raw.lower().startswith("basic "):
|
||||
return None
|
||||
try:
|
||||
decoded = base64.b64decode(raw[6:].strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
return None
|
||||
if ":" not in decoded:
|
||||
return None
|
||||
username, password = decoded.split(":", 1)
|
||||
if not username or not password:
|
||||
return None
|
||||
try:
|
||||
username.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions",
|
||||
summary="Вход: Basic username:password; выдаёт сессию",
|
||||
response_model=Session,
|
||||
status_code=201,
|
||||
)
|
||||
def create_session(request: Request) -> Session:
|
||||
parsed = _parse_basic_header(request)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
username, password = parsed
|
||||
user = storage.verify_credentials(username, password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token, expires_at = storage.create_session(user.id, _ttl_seconds())
|
||||
return Session(token=token, token_type="Bearer", expires_at=expires_at, user=user)
|
||||
|
||||
|
||||
@router.delete(
|
||||
path="/sessions/current",
|
||||
summary="Отозвать текущую сессию",
|
||||
status_code=204,
|
||||
)
|
||||
def revoke_session(request: Request) -> None:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
token = auth[7:].strip()
|
||||
if not token or storage.get_session_user(token) is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
storage.revoke_session(token)
|
||||
return None
|
||||
@@ -0,0 +1,94 @@
|
||||
import base64
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple[datetime, UUID]:
|
||||
"""Курсор привязан к пользователю. Любая порча → 400, не 500."""
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode()).decode()
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if data.get("user_id") != str(user_id):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
created_at = datetime.fromisoformat(data["created_at"])
|
||||
chat_id = UUID(data["id"])
|
||||
except (KeyError, ValueError, TypeError):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return created_at, chat_id
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
summary="Создать чат",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
user_id = user.id
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
return storage.create_chat(payload.title, list(payload.member_ids))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
summary="Получить список чатов текущего пользователя",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
user_id = user.id
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
ccreated, cid = _decode_cursor(user_id, cursor)
|
||||
ccreated_iso = ccreated.isoformat()
|
||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated_iso, str(cid))]
|
||||
page = chats[:limit]
|
||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||
return ChatPage(items=page, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}",
|
||||
summary="Получить доступный чат по идентификатору",
|
||||
response_model=Chat,
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user.id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
@@ -0,0 +1,52 @@
|
||||
from fastapi import APIRouter
|
||||
from ..models.schemas import Health
|
||||
from ..storage import db as _db
|
||||
from ..storage import s3 as _s3
|
||||
from ..storage.sessions import _redis_client, _store
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/live",
|
||||
summary="Проверка жизнеспособности процесса",
|
||||
response_model=Health,
|
||||
)
|
||||
def liveness() -> Health:
|
||||
"""Процесс жив"""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/ready",
|
||||
summary="Проверка готовности принимать трафик",
|
||||
response_model=Health,
|
||||
)
|
||||
def readiness() -> Health:
|
||||
"""200, если PostgreSQL, Redis (в режиме redis) и S3 доступны.
|
||||
|
||||
При недоступности зависимости выбрасываем RuntimeError("*_unavailable"),
|
||||
main.py конвертирует его в 503 с телом Error из contracts/openapi.json.
|
||||
Все проверки — с короткими таймаутами, чтобы не зависать надолго.
|
||||
"""
|
||||
try:
|
||||
with _db.connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Пул уже проверяет живость соединения (check_connection) и короткий
|
||||
# timeout=3.0; здесь лишь превращаем любую ошибку БД в 503, чтобы
|
||||
# после рестарта PostgreSQL readiness быстро возвращался в 200.
|
||||
raise RuntimeError("db_unavailable: %s" % type(exc).__name__) from exc
|
||||
# Redis (в режиме redis)
|
||||
if _store() == "redis":
|
||||
_redis_client().ping()
|
||||
# S3: HEAD несуществующего ключа. 404/None → S3 доступен.
|
||||
# Короткий таймаут клиента гарантирует быстрый ответ, а ошибка
|
||||
# преобразуется в RuntimeError("s3_unavailable") → 503.
|
||||
try:
|
||||
_s3.head_object("attachments/__health_probe__")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise RuntimeError("s3_unavailable: %s" % type(exc).__name__) from exc
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,141 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
# Контракт: Idempotency-Key ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
_IDEMPOTENCY_ALLOWED = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._:-")
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id),
|
||||
"created_at": message.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("chat_id") != str(chat_id):
|
||||
raise ValueError("cursor_chat_mismatch")
|
||||
return datetime.fromisoformat(data["created_at"]), UUID(data["id"])
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
def _canonical_body_hash(payload: CreateMessage) -> str:
|
||||
"""sha256 канонизированного JSON.
|
||||
|
||||
Поле attachment_ids присутствует в модели со значением по умолчанию [],
|
||||
поэтому payload {"text":"x"} и {"text":"x","attachment_ids":[]} дают
|
||||
одинаковый model_dump и одинаковый хэш — как требует контракт.
|
||||
"""
|
||||
data = payload.model_dump(mode="json")
|
||||
canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Отправить сообщение в чат",
|
||||
response_model=Message,
|
||||
status_code=201,
|
||||
)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user: User = Depends(current_user),
|
||||
idempotency_key: str = Header(..., alias="Idempotency-Key"),
|
||||
) -> Message:
|
||||
# Строго ASCII, как требует контракт: isalnum() пропускает кириллицу.
|
||||
if not (1 <= len(idempotency_key) <= 128):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if not all(c in _IDEMPOTENCY_ALLOWED for c in idempotency_key):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
_require_member(chat_id, user.id)
|
||||
|
||||
text = payload.text or ""
|
||||
attachment_ids = list(payload.attachment_ids)
|
||||
|
||||
# Контракт: text (непустой) ИЛИ attachment_ids (>=1).
|
||||
if text.strip() == "" and not attachment_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Все вложения должны принадлежать этому чату.
|
||||
if attachment_ids:
|
||||
found = storage.list_attachments_by_ids(attachment_ids, chat_id)
|
||||
if len(found) != len(attachment_ids):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
for aid in attachment_ids:
|
||||
att, _key = found[aid]
|
||||
if att.status == "failed":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
method = "POST"
|
||||
path = "/api/v1/chats/%s/messages" % chat_id
|
||||
body_hash = _canonical_body_hash(payload)
|
||||
|
||||
# Атомарная операция: INSERT ключа + INSERT сообщения + UPDATE ключа
|
||||
# в ОДНОЙ транзакции. Сбой между ними невозможен: либо всё, либо ничего.
|
||||
state, message, info = storage.add_message_idempotent(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=text,
|
||||
attachment_ids=attachment_ids,
|
||||
user_id=user.id,
|
||||
method=method,
|
||||
path=path,
|
||||
key=idempotency_key,
|
||||
body_hash=body_hash,
|
||||
)
|
||||
|
||||
if state == "created":
|
||||
return message
|
||||
|
||||
if state == "retry":
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
# state == "replay"
|
||||
if info["body_hash"] != body_hash:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
if info["response_status"] == 0:
|
||||
# Строка от старой версии кода: не зависаем, отдаём 503.
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
return Message.model_validate(info["response_body"])
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Получить историю сообщений чата",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию"""
|
||||
_require_member(chat_id, user.id)
|
||||
after = _decode_cursor(chat_id, cursor) if cursor else None
|
||||
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
|
||||
has_more = len(rows) > limit
|
||||
items = rows[:limit]
|
||||
next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,24 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import HTTPException, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from ..models.schemas import User
|
||||
from ..storage.postgres import storage
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth")
|
||||
|
||||
|
||||
def current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Security(bearer_scheme),
|
||||
) -> User:
|
||||
"""Достаёт Bearer-токен и возвращает владельца сессии.
|
||||
|
||||
Basic на бизнес-endpoint не принимается, X-User-Id игнорируется.
|
||||
"""
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
user = storage.get_session_user(credentials.credentials)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user
|
||||
@@ -0,0 +1,31 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from ..models.schemas import CreateUser, User
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/users",
|
||||
summary="Создать пользователя",
|
||||
response_model=User,
|
||||
status_code=201,
|
||||
)
|
||||
def register_user(payload: CreateUser) -> User:
|
||||
"""Публичная регистрация. Пробельные display_name/password отсекаются
|
||||
валидаторами схемы; сюда попадают только валидные значения."""
|
||||
try:
|
||||
return storage.create_user(payload.username, payload.display_name, payload.password)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/users/me",
|
||||
summary="Получить текущего пользователя",
|
||||
response_model=User,
|
||||
)
|
||||
def current_user_me(user: User = Depends(current_user)) -> User:
|
||||
"""Текущий пользователь по Bearer-сессии."""
|
||||
return user
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from opentelemetry import trace as _otel_trace
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||
|
||||
|
||||
# Базовый логгер: реальный формат выставляет telemetry.install_log_format()
|
||||
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool()
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
os.environ.get("SESSION_STORE", "postgres"),
|
||||
INSTANCE_ID,
|
||||
)
|
||||
yield
|
||||
close_pool()
|
||||
logger.info("event=shutdown_complete instance_id=%s", INSTANCE_ID)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab6",
|
||||
version="1.6.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
# OTel инициализация и FastAPI auto-instrumentation.
|
||||
init_telemetry("messenger-api", "1.6.0")
|
||||
|
||||
|
||||
# --- Метрики HTTP ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
unit="1",
|
||||
)
|
||||
# Явные границы бакетов в СЕКУНДАХ, с разрешением в миллисекундном диапазоне
|
||||
# и вокруг порога SLO 2s (upload p95 alert). Дефолтные экспоненциальные
|
||||
# бакеты (0, 5, 10, 25, …) грубы: миллисекундные запросы попадали в один
|
||||
# широкий bucket, а histogram_quantile интерполировал ложные секунды.
|
||||
_HTTP_DURATION_BUCKETS = [
|
||||
0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02, 0.03, 0.05,
|
||||
0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0,
|
||||
]
|
||||
_http_hist = meter("messenger").create_histogram(
|
||||
"http_request_duration_seconds",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
explicit_bucket_boundaries_advisory=_HTTP_DURATION_BUCKETS,
|
||||
)
|
||||
|
||||
# Фильтр: убираем реальные UUID из маршрута → route template.
|
||||
import re as _re
|
||||
_ROUTE_UUID_RE = _re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
|
||||
|
||||
def _route_template(path: str) -> str:
|
||||
return _ROUTE_UUID_RE.sub("{id}", path)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
||||
app.openapi_schema = schema
|
||||
return schema
|
||||
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
# Отдельный tracer для событийного span в middleware. Он создаётся как child
|
||||
# SERVER span, который создаёт OTel FastAPI instrumentation ниже.
|
||||
# ВАЖНО: FastAPIInstrumentor.instrument_app(app) вызывается ПОСЛЕ объявления
|
||||
# middleware, поэтому OTel ASGI middleware оказывается внешним: он извлекает
|
||||
# W3C traceparent из входящих headers, продолжает внешний trace и создаёт
|
||||
# SERVER span. Наш middleware выполняется внутри него, создаёт http.request
|
||||
# как INTERNAL child, и логи/метрики берут корректный trace_id.
|
||||
_http_tracer = tracer("app.http")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурированный лог + метрики.
|
||||
|
||||
Лог event=http пишется ВНУТРИ активного span (`http.request`), он
|
||||
child SERVER span от OTel auto-instrumentation, поэтому trace_id
|
||||
корректно связывает лог с внешним trace.
|
||||
"""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
route = _route_template(request.url.path)
|
||||
|
||||
# http.request — INTERNAL child текущего (SERVER) span, созданного OTel
|
||||
# auto-instrumentation. Parent берётся из активного контекста: входящий
|
||||
# traceparent уже извлечён ASGI middleware.
|
||||
with _http_tracer.start_as_current_span(
|
||||
"http.request",
|
||||
attributes={
|
||||
"http.method": request.method,
|
||||
"http.route": route,
|
||||
},
|
||||
) as span:
|
||||
response = await call_next(request)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
span.set_attribute("http.status_class", status_class)
|
||||
span.set_attribute("http.status_code", response.status_code)
|
||||
|
||||
# Лог ВНУТРИ span → record.trace_id валидный, Loki получает
|
||||
# корреляцию с Tempo.
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s "
|
||||
"request_id=%s instance_id=%s",
|
||||
request.method, request.url.path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# FastAPI auto-instrumentation ДОЛЖНА быть установлена ПОСЛЕ пользовательского
|
||||
# @app.middleware("http"), чтобы оказаться внешним middleware и создать SERVER
|
||||
# span с корректным parent из входного traceparent. Этот вызов также
|
||||
# инструментирует httpx/requests client-вызовы внутри приложения.
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Обработчики ошибок (без изменений) ---
|
||||
_ERROR_CODES = {
|
||||
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",
|
||||
}
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(status_code: int, message: str, request_id: str,
|
||||
path: str = "") -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Ошибка"
|
||||
return _error_response(exc.status_code, message, request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return _error_response(400, "Неверный запрос", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "db_unavailable" in text:
|
||||
logger.error("event=db_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
if "s3_unavailable" in text:
|
||||
logger.error("event=s3_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error("event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
server.run()
|
||||
@@ -0,0 +1,163 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
|
||||
|
||||
|
||||
def _to_z(dt: datetime) -> str:
|
||||
"""RFC 3339 UTC с Z, как требует contracts/README.md."""
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
dt = dt.astimezone(timezone.utc)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _not_blank(value: str) -> str:
|
||||
"""Контракт: обязательные строки не состоят только из пробельных символов."""
|
||||
if value is None or value.strip() == "":
|
||||
raise ValueError("must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
status: str
|
||||
|
||||
|
||||
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=12, max_length=128)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def _display_name_not_blank(cls, v: str) -> str:
|
||||
return _not_blank(v)
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def _password_not_blank(cls, v: str) -> str:
|
||||
return _not_blank(v)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def _title_not_blank(cls, v: str) -> str:
|
||||
return _not_blank(v)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: List[UUID]
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""text может быть пустым, если есть хотя бы одно вложение (lab4)."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(default="", max_length=4000)
|
||||
attachment_ids: List[UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def _unique_attachments(cls, v: List[UUID]) -> List[UUID]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("duplicate attachment_ids")
|
||||
return v
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: List[UUID] = Field(default_factory=list)
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
@field_serializer("expires_at")
|
||||
def _ser_expires_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str # "ready"
|
||||
variants: List[Variant] = Field(default_factory=list)
|
||||
error_code: Optional[str] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
@field_serializer("updated_at")
|
||||
def _ser_updated_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Outbox worker lab5/lab6: publish неопубликованных job в RabbitMQ с трейсингом.
|
||||
|
||||
lab6: payload строки outbox содержит traceparent/tracestate, снятые в момент
|
||||
upload-запроса API. Восстанавливаем контекст, создаём span job.publish как
|
||||
child upload-span и инжектим обновлённый traceparent в headers сообщения.
|
||||
|
||||
Лог event=outbox_published пишется ВНУТРИ span job.publish, чтобы в Loki
|
||||
попадал настоящий trace_id (корреляция лог↔trace).
|
||||
"""
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import QUEUE, publish_job
|
||||
from .telemetry import init_telemetry
|
||||
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
log = logging.getLogger("outbox")
|
||||
|
||||
_stop = False
|
||||
_tracer = trace.get_tracer("outbox")
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
init_telemetry("messenger-outbox", "1.6.0")
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
global _stop
|
||||
log.info("event=sigterm_received signal=%s", signum)
|
||||
_stop = True
|
||||
|
||||
|
||||
def _extract_parent(payload: dict) -> otel_context.Context:
|
||||
carrier: dict[str, str] = {}
|
||||
if payload.get("traceparent"):
|
||||
carrier["traceparent"] = str(payload["traceparent"])
|
||||
if payload.get("tracestate"):
|
||||
carrier["tracestate"] = str(payload["tracestate"])
|
||||
if not carrier:
|
||||
return otel_context.Context()
|
||||
try:
|
||||
return _propagator.extract(carrier=carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=trace_parent_parse_failed type=%s", type(exc).__name__)
|
||||
return otel_context.Context()
|
||||
|
||||
|
||||
def _publish_with_trace(payload: dict, outbox_id: int) -> None:
|
||||
"""Публикует payload; mark_published и лог — внутри span."""
|
||||
parent_ctx = _extract_parent(payload)
|
||||
carrier: dict[str, str] = {}
|
||||
with _tracer.start_as_current_span(
|
||||
"job.publish",
|
||||
context=parent_ctx,
|
||||
kind=SpanKind.PRODUCER,
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"job.id": str(payload.get("job_id", "")),
|
||||
"job.type": str(payload.get("type", "unknown")),
|
||||
"outbox.id": int(outbox_id),
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
try:
|
||||
_propagator.inject(carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=trace_inject_failed type=%s", type(exc).__name__)
|
||||
carrier = {}
|
||||
publish_job(payload, extra_headers=carrier)
|
||||
storage.mark_outbox_published(outbox_id)
|
||||
# Лог внутри span → record.trace_id валидный.
|
||||
log.info("event=outbox_published id=%s job_id=%s",
|
||||
outbox_id, payload.get("job_id"))
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
raise
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
log.info("event=outbox_start")
|
||||
|
||||
while not _stop:
|
||||
try:
|
||||
rows = storage.list_unpublished_outbox(limit=50)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=outbox_select_failed type=%s msg=%s",
|
||||
type(exc).__name__, str(exc)[:300])
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
for outbox_id, payload in rows:
|
||||
if _stop:
|
||||
break
|
||||
try:
|
||||
_publish_with_trace(payload, outbox_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning(
|
||||
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||
)
|
||||
time.sleep(2)
|
||||
break
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
close_pool()
|
||||
log.info("event=outbox_stop")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
log.error("event=outbox_fatal\n%s", traceback.format_exc())
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,212 @@
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _dsn() -> str:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise RuntimeError("DATABASE_URL is not set")
|
||||
return dsn
|
||||
|
||||
|
||||
def init_pool() -> None:
|
||||
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
_pool = ConnectionPool(
|
||||
conninfo=_dsn(),
|
||||
min_size=2,
|
||||
max_size=10,
|
||||
# Короткий таймаут получения соединения из пула: readiness/бизнес-запрос
|
||||
# при мёртвой БД должен быстро вернуть 503, а не висеть.
|
||||
timeout=3.0,
|
||||
max_idle=300.0,
|
||||
# check: перед выдачей соединения проверяем его живость; мёртвые
|
||||
# соединения после рестарта PostgreSQL отбрасываются, пул сам
|
||||
# открывает новые — readiness восстанавливается без рестарта API.
|
||||
check=ConnectionPool.check_connection,
|
||||
# Раз в 30с фоновый worker пула добивает min_size живыми соединениями,
|
||||
# чтобы после старта БД готовность вернулась в пределах окна теста.
|
||||
reconnect_timeout=30.0,
|
||||
kwargs={"options": "-c statement_timeout=5000"},
|
||||
open=True,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
"""Соединение из пула; autocommit=False для явных транзакций."""
|
||||
if _pool is None:
|
||||
init_pool()
|
||||
assert _pool is not None
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- sessions остаются как fallback, если SESSION_STORE=postgres.
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- lab3: общая идемпотентность POST /messages.
|
||||
-- scope: user_id + method + path + key (см. contracts/README.md).
|
||||
-- body_hash — sha256 канонизированного JSON без attachment_ids=[], чтобы
|
||||
-- отличать повтор «того же» body (201, тот же Message) от «другого» (409).
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
body_hash TEXT NOT NULL,
|
||||
response_status INT NOT NULL,
|
||||
response_body JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||
ON idempotency_keys (created_at);
|
||||
|
||||
-- lab4: вложения
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL, -- queued/processing/ready/failed
|
||||
error_code TEXT,
|
||||
processing_until TIMESTAMPTZ, -- lease для worker (lab5)
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_chat
|
||||
ON attachments (chat_id);
|
||||
|
||||
-- связь сообщение↔вложение (порядок сохраняем)
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
position INT NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
||||
ON message_attachments (message_id, position);
|
||||
|
||||
-- lab5: варианты обработки (идемпотентность по (attachment_id, pipeline_version, variant))
|
||||
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version INT NOT NULL,
|
||||
variant TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
width INT NOT NULL,
|
||||
height INT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (attachment_id, pipeline_version, variant)
|
||||
);
|
||||
|
||||
-- lab5 level 4: transactional outbox (разрыв COMMIT → publish)
|
||||
CREATE TABLE IF NOT EXISTS outbox (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
job_id UUID NOT NULL UNIQUE,
|
||||
payload JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
published_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_outbox_unpublished
|
||||
ON outbox (id) WHERE published_at IS NULL;
|
||||
"""
|
||||
|
||||
|
||||
def init_schema() -> None:
|
||||
"""Идемпотентная миграция: безопасно вызывать многократно.
|
||||
|
||||
Вызывается ОДИН РАЗ отдельным one-shot сервисом migrate
|
||||
(см. compose.yaml). Реплики API миграции больше не выполняют:
|
||||
они ждут service_completed_successfully.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(SCHEMA_SQL)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def run_migrations() -> None:
|
||||
"""Точка входа для one-shot migrate-контейнера.
|
||||
|
||||
Поднимает пул, применяет схему, закрывает пул. Завершается с кодом 0
|
||||
при успехе — этого достаточно для service_completed_successfully.
|
||||
"""
|
||||
init_pool()
|
||||
try:
|
||||
init_schema()
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Запуск: python -m app.storage.db
|
||||
# (в compose.yaml — command: ["python", "-m", "app.storage.db"])
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
log = logging.getLogger("migrate")
|
||||
log.info("event=migrations_start")
|
||||
run_migrations()
|
||||
log.info("event=migrations_done")
|
||||
@@ -0,0 +1,177 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
"""Время сервера в UTC с суффиксом Z на выходе."""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N,
|
||||
r=_SCRYPT_R,
|
||||
p=_SCRYPT_P,
|
||||
dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P,
|
||||
salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов, сообщений и сессий. Все данные исчезают при перезапуске процесса"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self._users: Dict[UUID, User] = {}
|
||||
self._usernames: Dict[str, UUID] = {}
|
||||
self._passwords: Dict[UUID, str] = {}
|
||||
self._chats: Dict[UUID, Chat] = {}
|
||||
self._messages: Dict[UUID, List[Message]] = {}
|
||||
# token -> (user_id, expires_at)
|
||||
self._sessions: Dict[str, tuple] = {}
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._usernames:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._usernames[username] = user.id
|
||||
self._passwords[user.id] = _hash_password(password)
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
if uid is None:
|
||||
return None
|
||||
stored = self._passwords.get(uid)
|
||||
if not stored or not _verify_password(password, stored):
|
||||
return None
|
||||
return self._users.get(uid)
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
with self._lock:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
self._sessions[token] = (user_id, expires_at)
|
||||
return token, expires_at
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
entry = self._sessions.get(token)
|
||||
if entry is None:
|
||||
return None
|
||||
user_id, expires_at = entry
|
||||
if expires_at <= now_utc():
|
||||
self._sessions.pop(token, None)
|
||||
return None
|
||||
return self._users.get(user_id)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with self._lock:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock:
|
||||
for uid in member_ids:
|
||||
if uid not in self._users:
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._chats[chat.id] = chat
|
||||
self._messages[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with self._lock:
|
||||
chats = [c for c in self._chats.values() if user_id in c.member_ids]
|
||||
chats.sort(key=lambda c: (c.created_at, str(c.id)))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
"""Улучшение Трека 1: список сообщений хранится уже отсортированным.
|
||||
created_at монотонен в пределах одного процесса, поэтому append
|
||||
сохраняет порядок (created_at, id) по возрастанию — сортировка на
|
||||
чтении не нужна. При конкурентных вставках под RLock порядок
|
||||
сохраняется, но монотонность часов не гарантируется контрактом."""
|
||||
with self._lock:
|
||||
message = Message(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._messages.setdefault(chat_id, []).append(message)
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with self._lock:
|
||||
# Без пересортировки: список уже в порядке (created_at, id).
|
||||
return list(self._messages.get(chat_id, []))
|
||||
|
||||
|
||||
storage = MemoryStorage() # единственный экземпляр хранилища на процесс
|
||||
@@ -0,0 +1,614 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Attachment, Chat, Message, User, Variant
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
get_session_user as _sess_get,
|
||||
revoke_session as _sess_revoke,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P, salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _row_to_user(row) -> User:
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
||||
|
||||
|
||||
def _row_to_chat(row, member_ids: List[UUID]) -> Chat:
|
||||
return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2])
|
||||
|
||||
|
||||
def _row_to_message(row, attachment_ids: List[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row[0], chat_id=row[1], sender_id=row[2],
|
||||
text=row[3], created_at=row[4],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
def _row_to_attachment(row, variants: Optional[list] = None) -> Attachment:
|
||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
# status, error_code, created_at, updated_at
|
||||
return Attachment(
|
||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||
sha256=row[6], status=row[7], variants=variants or [],
|
||||
error_code=row[8],
|
||||
created_at=row[9], updated_at=row[10],
|
||||
)
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
"""Потокобезопасная обёртка; параллелизм обеспечивает PostgreSQL."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(), username=username,
|
||||
display_name=display_name, created_at=now_utc(),
|
||||
)
|
||||
try:
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(user.id, user.username, user.display_name,
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
except Exception as exc:
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
conn.commit()
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash"
|
||||
" FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if not _verify_password(password, row[4]):
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
return _sess_get(token)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# проверяем всех участников
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||
(list(member_ids),),
|
||||
)
|
||||
found = {r[0] for r in cur.fetchall()}
|
||||
if len(found) != len(set(member_ids)):
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(), title=title,
|
||||
member_ids=list(member_ids), created_at=now_utc(),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat.id, chat.title, chat.created_at),
|
||||
)
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat.id, uid) for uid in member_ids],
|
||||
)
|
||||
conn.commit()
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(chat_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
return _row_to_chat(row, members)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c"
|
||||
" JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s ORDER BY c.created_at, c.id",
|
||||
(user_id,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
chats = []
|
||||
for row in rows:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (row[0],),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
chats.append(_row_to_chat(row, members))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def _load_message_attachments(self, cur, message_ids: List[UUID]) -> dict[UUID, List[UUID]]:
|
||||
if not message_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"SELECT message_id, attachment_id, position FROM message_attachments"
|
||||
" WHERE message_id = ANY(%s) ORDER BY message_id, position",
|
||||
(list(message_ids),),
|
||||
)
|
||||
result: dict[UUID, List[UUID]] = {}
|
||||
for mid, aid, _pos in cur.fetchall():
|
||||
result.setdefault(mid, []).append(aid)
|
||||
return result
|
||||
|
||||
def list_messages_page(
|
||||
self, chat_id: UUID, limit: int, after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, limit),
|
||||
)
|
||||
else:
|
||||
after_ts, after_id = after
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
ids = [r[0] for r in rows]
|
||||
att_map = self._load_message_attachments(cur, ids)
|
||||
return [_row_to_message(r, att_map.get(r[0], [])) for r in rows]
|
||||
|
||||
# ---------- Идемпотентность (lab3) ----------
|
||||
def add_message_idempotent(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: List[UUID],
|
||||
user_id: UUID,
|
||||
method: str,
|
||||
path: str,
|
||||
key: str,
|
||||
body_hash: str,
|
||||
) -> tuple[str, Optional[Message], Optional[dict]]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO idempotency_keys"
|
||||
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
||||
" VALUES (%s, %s, %s, %s, %s, 0, '{}'::jsonb)"
|
||||
" ON CONFLICT (user_id, method, path, key) DO NOTHING"
|
||||
" RETURNING key",
|
||||
(user_id, method, path, key, body_hash),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
|
||||
if won:
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
attachment_ids=list(attachment_ids),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(message.id, message.chat_id, message.sender_id,
|
||||
message.text, message.created_at),
|
||||
)
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
"INSERT INTO message_attachments"
|
||||
" (message_id, attachment_id, position)"
|
||||
" VALUES (%s, %s, %s)",
|
||||
[(message.id, aid, idx)
|
||||
for idx, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
body_json = _json.loads(message.model_dump_json())
|
||||
cur.execute(
|
||||
"UPDATE idempotency_keys"
|
||||
" SET response_status = %s, response_body = %s"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(201, _json.dumps(body_json),
|
||||
user_id, method, path, key),
|
||||
)
|
||||
conn.commit()
|
||||
return ("created", message, None)
|
||||
|
||||
cur.execute(
|
||||
"SELECT body_hash, response_status, response_body"
|
||||
" FROM idempotency_keys"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(user_id, method, path, key),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
if row is None:
|
||||
return ("retry", None, None)
|
||||
return (
|
||||
"replay",
|
||||
None,
|
||||
{
|
||||
"body_hash": row[0],
|
||||
"response_status": row[1],
|
||||
"response_body": row[2],
|
||||
},
|
||||
)
|
||||
|
||||
# ---------- Вложения ----------
|
||||
def create_attachment(self, attachment: Attachment, object_key: str) -> Attachment:
|
||||
"""lab4 fallback (синхронный ready). Не используется в lab5."""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, object_key,
|
||||
attachment.status, attachment.error_code,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def create_attachment_queued(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
staging_key: str,
|
||||
outbox_payload: dict,
|
||||
) -> Attachment:
|
||||
"""lab5: attachment в queued + строка outbox в ОДНОЙ транзакции."""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, processing_until,"
|
||||
" created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, staging_key,
|
||||
"queued", None, None,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(outbox_payload["job_id"], _json.dumps(outbox_payload)),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def claim_processing(self, attachment_id: UUID, lease_seconds: int = 60) -> bool:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing',"
|
||||
" processing_until=%s, updated_at=%s"
|
||||
" WHERE id=%s AND status IN ('queued','processing')"
|
||||
" RETURNING id",
|
||||
(now + timedelta(seconds=lease_seconds), now, attachment_id),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
return won
|
||||
|
||||
def recover_stuck_processing(self) -> int:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='queued', processing_until=NULL,"
|
||||
" updated_at=%s"
|
||||
" WHERE status='processing' AND processing_until IS NOT NULL"
|
||||
" AND processing_until < %s",
|
||||
(now, now),
|
||||
)
|
||||
count = cur.rowcount
|
||||
conn.commit()
|
||||
return count
|
||||
|
||||
def replay_failed_to_queued(self, attachment_id: UUID) -> str:
|
||||
"""Операторский replay: failed → queued с новой записью в outbox.
|
||||
|
||||
Возвращает:
|
||||
- "requeued" — статус был failed, переведён в queued и запланирован job;
|
||||
- "already" — запись уже queued/processing/ready (защита готовых), ничего не меняем;
|
||||
- "missing" — такого вложения нет.
|
||||
|
||||
Ключ эффекта (attachment_id, pipeline_version, variant) и ON CONFLICT
|
||||
в finalize_ready гарантируют, что повтор не создаст дублей вариантов.
|
||||
Новый job_id и строка outbox публикуются отдельным процессом outbox,
|
||||
поэтому разрыв между COMMIT и publish закрыт тем же механизмом, что и при upload.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT status FROM attachments WHERE id = %s FOR UPDATE",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
conn.rollback()
|
||||
return "missing"
|
||||
status = row[0]
|
||||
if status != "failed":
|
||||
conn.rollback()
|
||||
return "already"
|
||||
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='queued', error_code=NULL,"
|
||||
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||
(now, attachment_id),
|
||||
)
|
||||
|
||||
job_id = uuid4()
|
||||
payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
cur.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(job_id, _json.dumps(payload)),
|
||||
)
|
||||
conn.commit()
|
||||
return "requeued"
|
||||
|
||||
def finalize_ready(
|
||||
self,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
variants: list[dict],
|
||||
) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
original = next(v for v in variants if v["name"] == "original")
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='ready', error_code=NULL,"
|
||||
" object_key=%s, processing_until=NULL, updated_at=%s"
|
||||
" WHERE id=%s",
|
||||
(original["object_key"], now_utc(), attachment_id),
|
||||
)
|
||||
for v in variants:
|
||||
if v["name"] == "original":
|
||||
continue
|
||||
cur.execute(
|
||||
"INSERT INTO attachment_variants"
|
||||
" (attachment_id, pipeline_version, variant, object_key,"
|
||||
" content_type, size_bytes, width, height, sha256)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
|
||||
" ON CONFLICT (attachment_id, pipeline_version, variant)"
|
||||
" DO NOTHING",
|
||||
(
|
||||
attachment_id, pipeline_version, v["name"],
|
||||
v["object_key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def finalize_failed(self, attachment_id: UUID, error_code: str) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code=%s,"
|
||||
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||
(error_code, now_utc(), attachment_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||
pair = self.get_attachment_with_key(attachment_id)
|
||||
return pair[0] if pair else None
|
||||
|
||||
def get_attachment_with_key(
|
||||
self, attachment_id: UUID
|
||||
) -> Optional[tuple[Attachment, str]]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
att = _row_to_attachment(row[:11], self.get_attachment_variants(attachment_id))
|
||||
return att, row[11]
|
||||
|
||||
def list_attachments_by_ids(
|
||||
self, ids: List[UUID], chat_id: UUID
|
||||
) -> dict[UUID, tuple[Attachment, str]]:
|
||||
if not ids:
|
||||
return {}
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE chat_id = %s AND id = ANY(%s)",
|
||||
(chat_id, list(ids)),
|
||||
)
|
||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||
for row in cur.fetchall():
|
||||
att = _row_to_attachment(row[:11])
|
||||
result[row[0]] = (att, row[11])
|
||||
return result
|
||||
|
||||
def delete_attachment(self, attachment_id: UUID) -> None:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||
conn.commit()
|
||||
|
||||
def get_attachment_variants(self, attachment_id: UUID) -> list[dict]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT variant, content_type, size_bytes, width, height, sha256"
|
||||
" FROM attachment_variants WHERE attachment_id=%s"
|
||||
" ORDER BY variant",
|
||||
(attachment_id,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"name": r[0], "content_type": r[1], "size_bytes": r[2],
|
||||
"width": r[3], "height": r[4], "sha256": r[5],
|
||||
}
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
def get_staging_key(self, attachment_id: UUID) -> Optional[str]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
# ---------- Outbox (lab5 level 4) ----------
|
||||
def list_unpublished_outbox(self, limit: int = 100) -> list[tuple[int, dict]]:
|
||||
"""Возвращает [(outbox_id, payload_dict), ...].
|
||||
|
||||
Всегда dict; если payload в БД пришёл строкой (например, из старой
|
||||
версии), распаковываем через json.loads.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, payload FROM outbox WHERE published_at IS NULL"
|
||||
" ORDER BY id LIMIT %s",
|
||||
(limit,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
result: list[tuple[int, dict]] = []
|
||||
for r in rows:
|
||||
raw = r[1]
|
||||
if isinstance(raw, dict):
|
||||
payload = raw
|
||||
else:
|
||||
payload = _json.loads(raw)
|
||||
if not isinstance(payload, dict):
|
||||
# защита от мусора — пропустить
|
||||
continue
|
||||
result.append((int(r[0]), payload))
|
||||
return result
|
||||
|
||||
def mark_outbox_published(self, outbox_id: int) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE outbox SET published_at=now() WHERE id=%s",
|
||||
(outbox_id,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
@@ -0,0 +1,155 @@
|
||||
"""RabbitMQ: topology, publisher with confirms, consumer с manual ack.
|
||||
|
||||
- Основная очередь: durable quorum queue.
|
||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||
- DLQ: финальные ошибки и исчерпанные retry.
|
||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||
- lab6: extra_headers для traceparent/tracestate.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
import pika
|
||||
|
||||
log = logging.getLogger("rabbit")
|
||||
|
||||
EXCHANGE = "messenger.attachments"
|
||||
QUEUE = "attachment.process.v1"
|
||||
RETRY_EXCHANGE = "messenger.attachments.retry"
|
||||
DLX = "messenger.attachments.dlx"
|
||||
DLQ = "attachment.process.v1.dlq"
|
||||
|
||||
RETRY_DELAYS = [5, 15, 60]
|
||||
MAX_ATTEMPTS = len(RETRY_DELAYS) + 1
|
||||
|
||||
_topology_ready = False
|
||||
_topology_lock = threading.Lock()
|
||||
|
||||
|
||||
def _url() -> str:
|
||||
return os.environ.get("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/%2F")
|
||||
|
||||
|
||||
def connection_params() -> pika.ConnectionParameters:
|
||||
return pika.URLParameters(_url())
|
||||
|
||||
|
||||
def connect() -> pika.BlockingConnection:
|
||||
return pika.BlockingConnection(connection_params())
|
||||
|
||||
|
||||
def setup_topology(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
channel.exchange_declare(EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(RETRY_EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(DLX, exchange_type="direct", durable=True)
|
||||
|
||||
channel.queue_declare(DLQ, durable=True, arguments={"x-queue-type": "quorum"})
|
||||
channel.queue_bind(DLQ, DLX, routing_key=DLQ)
|
||||
|
||||
channel.queue_declare(
|
||||
QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": DLX,
|
||||
"x-dead-letter-routing-key": DLQ,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE)
|
||||
|
||||
for delay in RETRY_DELAYS:
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
channel.queue_declare(
|
||||
qname,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-message-ttl": delay * 1000,
|
||||
"x-dead-letter-exchange": EXCHANGE,
|
||||
"x-dead-letter-routing-key": QUEUE,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(qname, RETRY_EXCHANGE, routing_key=qname)
|
||||
|
||||
|
||||
def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
global _topology_ready
|
||||
if _topology_ready:
|
||||
return
|
||||
with _topology_lock:
|
||||
if _topology_ready:
|
||||
return
|
||||
setup_topology(ch)
|
||||
_topology_ready = True
|
||||
|
||||
|
||||
def publish_job(payload: dict, extra_headers: Optional[dict] = None) -> None:
|
||||
"""Публикация job с publisher confirm. extra_headers — traceparent."""
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
headers = dict(extra_headers or {})
|
||||
ch.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=QUEUE,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers or None,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_retry(payload: dict, retry_count: int) -> None:
|
||||
idx = min(retry_count - 1, len(RETRY_DELAYS) - 1)
|
||||
delay = RETRY_DELAYS[idx]
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
headers = dict(payload.get("_headers") or {})
|
||||
headers["x-retry-count"] = retry_count
|
||||
clean = {k: v for k, v in payload.items() if k != "_headers"}
|
||||
body = json.dumps(clean, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=RETRY_EXCHANGE,
|
||||
routing_key=qname,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_dlq(payload: dict) -> None:
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=DLX,
|
||||
routing_key=DLQ,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=2, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Операторский replay failed-задач: failed → queued + запись в outbox.
|
||||
|
||||
Использование:
|
||||
python -m app.storage.replay_failed <attachment_id> [<attachment_id> ...]
|
||||
python -m app.storage.replay_failed --all-failed
|
||||
|
||||
Защита:
|
||||
- переводит ТОЛЬКО failed; queued/processing/ready не трогает (возвращает "already");
|
||||
- новая строка outbox с новым job_id — публикация через существующий outbox-процесс;
|
||||
- идемпотентность эффекта по (attachment_id, pipeline_version, variant)
|
||||
не даёт создать дубли вариантов, если повторная обработка уже была выполнена.
|
||||
Логи пишутся только с ID и статусом, без секретов и содержимого файлов.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from .db import init_pool, close_pool
|
||||
from .postgres import storage
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("replay_failed")
|
||||
|
||||
|
||||
def _parse_args(argv):
|
||||
if not argv:
|
||||
print(
|
||||
"usage: python -m app.storage.replay_failed <attachment_id> [...] | --all-failed",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
if argv == ["--all-failed"]:
|
||||
return "all"
|
||||
ids = []
|
||||
for raw in argv:
|
||||
try:
|
||||
ids.append(uuid.UUID(raw))
|
||||
except ValueError:
|
||||
print("invalid attachment_id: %r" % raw, file=sys.stderr)
|
||||
return None
|
||||
return ids
|
||||
|
||||
|
||||
def _list_failed_ids() -> list:
|
||||
from .db import connection
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id FROM attachments WHERE status='failed' ORDER BY updated_at")
|
||||
return [r[0] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def main(argv) -> int:
|
||||
parsed = _parse_args(argv)
|
||||
if parsed is None:
|
||||
return 2
|
||||
init_pool()
|
||||
try:
|
||||
if parsed == "all":
|
||||
ids = _list_failed_ids()
|
||||
else:
|
||||
ids = parsed
|
||||
requeued = already = missing = 0
|
||||
for aid in ids:
|
||||
result = storage.replay_failed_to_queued(aid)
|
||||
if result == "requeued":
|
||||
requeued += 1
|
||||
log.info("event=replay_requeued attachment_id=%s", aid)
|
||||
elif result == "already":
|
||||
already += 1
|
||||
log.info("event=replay_skipped_not_failed attachment_id=%s", aid)
|
||||
else:
|
||||
missing += 1
|
||||
log.info("event=replay_missing attachment_id=%s", aid)
|
||||
log.info(
|
||||
"event=replay_done requested=%d requeued=%d skipped=%d missing=%d",
|
||||
len(ids), requeued, already, missing,
|
||||
)
|
||||
return 0 if missing == 0 else 1
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""S3-клиент (MinIO) для lab4/lab5.
|
||||
|
||||
Object key генерирует сервер:
|
||||
staging: staging/<chat_id>/<attachment_id>/original
|
||||
final: attachments/<chat_id>/<attachment_id>/original
|
||||
variant: attachments/<chat_id>/<attachment_id>/<variant>
|
||||
filename используется только для отображения, не в ключе.
|
||||
"""
|
||||
import os
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return os.environ["S3_ENDPOINT"]
|
||||
|
||||
|
||||
def _bucket() -> str:
|
||||
return os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def client():
|
||||
"""Клиент с прикладными credentials (не admin).
|
||||
|
||||
Явные короткие таймауты: connect/read — чтобы при недоступности S3
|
||||
запросы падали быстро и LB отдавал 503, а не 504 по своему timeout.
|
||||
"""
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_endpoint(),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=os.environ["S3_APP_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_APP_SECRET_KEY"],
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"max_attempts": 0},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def staging_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Staging — приватный prefix, worker читает отсюда."""
|
||||
return "staging/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Финальный ключ оригинала. Не зависит от filename."""
|
||||
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def variant_key(chat_id: UUID, attachment_id: UUID, variant: str) -> str:
|
||||
return "attachments/%s/%s/%s" % (chat_id, attachment_id, variant)
|
||||
|
||||
|
||||
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
||||
client().put_object(
|
||||
Bucket=_bucket(),
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
ContentLength=len(data),
|
||||
)
|
||||
|
||||
|
||||
def get_object(key: str):
|
||||
"""Возвращает (bytes, content_type). Бросает ClientError при отсутствии."""
|
||||
resp = client().get_object(Bucket=_bucket(), Key=key)
|
||||
body = resp["Body"].read()
|
||||
ctype = resp.get("ContentType") or "application/octet-stream"
|
||||
return body, ctype
|
||||
|
||||
|
||||
def delete_object(key: str) -> None:
|
||||
client().delete_object(Bucket=_bucket(), Key=key)
|
||||
|
||||
|
||||
def head_object(key: str) -> Optional[dict]:
|
||||
try:
|
||||
return client().head_object(Bucket=_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
def list_objects(prefix: str = "attachments/"):
|
||||
"""Итератор по объектам bucket. Используется cleanup-сервисом."""
|
||||
paginator = client().get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=_bucket(), Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
yield obj
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4 lab4/lab5).
|
||||
|
||||
- Orphan: объект в S3 есть, а метаданных/вариантов в БД нет.
|
||||
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
||||
- Missing: метаданные есть, объекта в S3 нет — warning.
|
||||
- Staging: объекты staging/ старше grace удаляются (не привязаны к текущей работе).
|
||||
- Также периодически возвращает зависшие processing в queued.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import s3
|
||||
from .db import connection, init_pool, close_pool
|
||||
from .postgres import storage
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("s3_cleanup")
|
||||
|
||||
|
||||
def _interval() -> int:
|
||||
try:
|
||||
return max(30, int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "300")))
|
||||
except ValueError:
|
||||
return 300
|
||||
|
||||
|
||||
def _grace() -> int:
|
||||
try:
|
||||
return max(0, int(os.environ.get("ORPHAN_GRACE_SECONDS", "3600")))
|
||||
except ValueError:
|
||||
return 3600
|
||||
|
||||
|
||||
def _known_keys() -> set[str]:
|
||||
"""Все ожидаемые object key: оригиналы + варианты."""
|
||||
keys: set[str] = set()
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id, chat_id, object_key FROM attachments")
|
||||
for aid, cid, okey in cur.fetchall():
|
||||
keys.add(okey)
|
||||
keys.add(s3.original_key(cid, aid))
|
||||
cur.execute("SELECT attachment_id, variant FROM attachment_variants")
|
||||
# нужен chat_id для variant_key
|
||||
# variants: отдельным запросом с join
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT a.chat_id, v.attachment_id, v.variant"
|
||||
" FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id"
|
||||
)
|
||||
for cid, aid, variant in cur.fetchall():
|
||||
keys.add(s3.variant_key(cid, aid, variant))
|
||||
return keys
|
||||
|
||||
|
||||
def _active_attachment_ids() -> set[str]:
|
||||
"""ID вложений в статусах queued/processing — их staging трогать нельзя."""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id FROM attachments WHERE status IN ('queued', 'processing')"
|
||||
)
|
||||
return {str(r[0]) for r in cur.fetchall()}
|
||||
|
||||
|
||||
def _run_once() -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
grace_cutoff = now - timedelta(seconds=_grace())
|
||||
|
||||
known = _known_keys()
|
||||
active_ids = _active_attachment_ids()
|
||||
orphan_deleted = 0
|
||||
missing = 0
|
||||
scanned = 0
|
||||
staging_deleted = 0
|
||||
|
||||
# attachments/ — orphan по known
|
||||
for obj in s3.list_objects("attachments/"):
|
||||
scanned += 1
|
||||
key = obj["Key"]
|
||||
if key in known:
|
||||
continue
|
||||
# Orphan: в S3 есть, в БД нет. Удаляем только старше grace period.
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
# Свежий объект — возможно in-flight upload; не трогаем.
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
orphan_deleted += 1
|
||||
log.info("event=orphan_deleted key=%s", key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=orphan_delete_failed key=%s type=%s",
|
||||
key, type(exc).__name__)
|
||||
|
||||
# staging/ — удаляем только старое И не принадлежащее активной задаче.
|
||||
# Ключ: staging/<chat_id>/<attachment_id>/original
|
||||
for obj in s3.list_objects("staging/"):
|
||||
key = obj["Key"]
|
||||
parts = key.split("/")
|
||||
# Ожидаем минимум 4 части: staging / chat_id / attachment_id / original
|
||||
if len(parts) < 4 or parts[0] != "staging":
|
||||
continue
|
||||
attachment_id = parts[2]
|
||||
if attachment_id in active_ids:
|
||||
# Задача ещё в queued/processing — staging нужен worker'у.
|
||||
continue
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
staging_deleted += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# missing
|
||||
for key in known:
|
||||
if s3.head_object(key) is None:
|
||||
missing += 1
|
||||
log.warning("event=missing_object key=%s", key)
|
||||
|
||||
# зависшие processing → queued
|
||||
try:
|
||||
recovered = storage.recover_stuck_processing()
|
||||
if recovered:
|
||||
log.info("event=stuck_processing_recovered count=%s", recovered)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=recover_stuck_failed type=%s", type(exc).__name__)
|
||||
|
||||
return {
|
||||
"scanned": scanned,
|
||||
"orphan_deleted": orphan_deleted,
|
||||
"missing": missing,
|
||||
"known": len(known),
|
||||
"staging_deleted": staging_deleted,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_pool()
|
||||
interval = _interval()
|
||||
log.info("event=cleanup_start interval_s=%s grace_s=%s", interval, _grace())
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
stats = _run_once()
|
||||
log.info(
|
||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s"
|
||||
" missing=%s staging_deleted=%s",
|
||||
stats["scanned"], stats["known"], stats["orphan_deleted"],
|
||||
stats["missing"], stats["staging_deleted"],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
||||
time.sleep(interval)
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Хранилище сессий. Redis (основной режим, lab2 level 4) или PostgreSQL (fallback).
|
||||
|
||||
Ключевое: при недоступности Redis поднимаем RuntimeError("redis_unavailable"),
|
||||
чтобы main.py отдал 503 unavailable, а не 500 internal_error.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from ..models.schemas import User
|
||||
from . import db as _db
|
||||
|
||||
try:
|
||||
import redis as _redis
|
||||
except ImportError: # pragma: no cover
|
||||
_redis = None
|
||||
|
||||
|
||||
_SESSION_PREFIX = "sess:"
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _store() -> str:
|
||||
return os.environ.get("SESSION_STORE", "redis").strip().lower()
|
||||
|
||||
|
||||
def _redis_client():
|
||||
"""Возвращает подключённый клиент Redis или поднимает RuntimeError.
|
||||
|
||||
RuntimeError("redis_unavailable: ...") ловит main.runtime_error_handler → 503.
|
||||
"""
|
||||
if _redis is None:
|
||||
raise RuntimeError("redis_unavailable: redis library is not installed")
|
||||
url = os.environ.get("REDIS_URL", "redis://redis:6379/0")
|
||||
try:
|
||||
client = _redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_timeout=2.0,
|
||||
socket_connect_timeout=2.0,
|
||||
)
|
||||
client.ping()
|
||||
return client
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
|
||||
|
||||
def _user_key(user_id: UUID) -> str:
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def create_session(user_id: UUID, ttl_seconds: int) -> tuple[str, datetime]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
payload = json.dumps({"user_id": _user_key(user_id), "expires_at": expires_at.isoformat()})
|
||||
try:
|
||||
# SETEX: TTL — сама суть Redis-сессий
|
||||
r.setex(_SESSION_PREFIX + token, ttl_seconds, payload)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
else:
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
return token, expires_at
|
||||
|
||||
|
||||
def get_session_user(token: str) -> Optional[User]:
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
try:
|
||||
raw = r.get(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
user_id = UUID(data["user_id"])
|
||||
expires_at = datetime.fromisoformat(data["expires_at"])
|
||||
except Exception:
|
||||
return None
|
||||
if expires_at <= now_utc():
|
||||
try:
|
||||
r.delete(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError:
|
||||
pass
|
||||
return None
|
||||
return _load_user(user_id)
|
||||
# postgres fallback
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
|
||||
" FROM sessions s JOIN users u ON u.id = s.user_id"
|
||||
" WHERE s.token = %s",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row[4] <= now_utc():
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
return None
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
||||
|
||||
|
||||
def revoke_session(token: str) -> None:
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
try:
|
||||
r.delete(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
return
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _load_user(user_id: UUID) -> Optional[User]:
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3]) if row else None
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Единая точка инициализации OpenTelemetry для API и worker.
|
||||
|
||||
- OTLP/HTTP → Collector (otel-collector:4318).
|
||||
- resource: service.name/version/instance.id/deployment.environment.name=lab.
|
||||
- LoggingFilter подставляет trace_id/span_id в каждую запись, чтобы они
|
||||
попадали и в stdout (видно глазами), и в Loki (в тексте строки) — это
|
||||
требование lab6 level4 (связь лога и trace).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
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
|
||||
|
||||
|
||||
_INITIALIZED = False
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||
|
||||
|
||||
def _resource(service_name: str, service_version: str) -> Resource:
|
||||
return Resource.create(
|
||||
{
|
||||
"service.name": service_name,
|
||||
"service.version": service_version,
|
||||
"service.instance.id": INSTANCE_ID,
|
||||
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _build_trace_provider(resource: Resource) -> TracerProvider:
|
||||
provider = TracerProvider(resource=resource)
|
||||
exporter = OTLPSpanExporter(endpoint=_endpoint() + "/v1/traces", timeout=5)
|
||||
provider.add_span_processor(
|
||||
BatchSpanProcessor(exporter, max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000)
|
||||
)
|
||||
return provider
|
||||
|
||||
|
||||
def _build_meter_provider(resource: Resource) -> MeterProvider:
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=_endpoint() + "/v1/metrics", timeout=5),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
return MeterProvider(resource=resource, metric_readers=[reader])
|
||||
|
||||
|
||||
def _build_logger_provider(resource: Resource) -> LoggerProvider:
|
||||
provider = LoggerProvider(resource=resource)
|
||||
provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=_endpoint() + "/v1/logs", timeout=5),
|
||||
max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000,
|
||||
)
|
||||
)
|
||||
return provider
|
||||
|
||||
|
||||
class TraceContextFilter(logging.Filter):
|
||||
"""Подставляет record.trace_id / record.span_id из активного span.
|
||||
|
||||
Если активного span нет — пишет "0"*32 и "0"*16, чтобы лог-формат
|
||||
оставался валидным (не падал с KeyError). Так же OTel сам поступает.
|
||||
"""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
span = trace.get_current_span()
|
||||
span_ctx = span.get_span_context() if span else None
|
||||
if span_ctx is not None and span_ctx.is_valid:
|
||||
record.trace_id = format(span_ctx.trace_id, "032x")
|
||||
record.span_id = format(span_ctx.span_id, "016x")
|
||||
else:
|
||||
record.trace_id = "0" * 32
|
||||
record.span_id = "0" * 16
|
||||
return True
|
||||
|
||||
|
||||
_LOG_FORMAT = (
|
||||
"%(asctime)s %(levelname)s %(name)s "
|
||||
"trace_id=%(trace_id)s span_id=%(span_id)s %(message)s"
|
||||
)
|
||||
|
||||
|
||||
def install_log_format() -> None:
|
||||
"""Единый формат логов API/worker/outbox.
|
||||
|
||||
Поля trace_id/span_id гарантированно существуют благодаря
|
||||
TraceContextFilter. Их наличие обеспечивает уровень 4 (корреляция
|
||||
логов и trace) и делает Loki-запросы `|= "trace_id="` рабочими.
|
||||
"""
|
||||
handler = logging.StreamHandler()
|
||||
handler.addFilter(TraceContextFilter())
|
||||
handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||
root = logging.getLogger()
|
||||
root.handlers = [handler]
|
||||
root.setLevel(logging.INFO)
|
||||
|
||||
|
||||
def init_telemetry(service_name: str, service_version: str = "1.6.0") -> None:
|
||||
"""Идемпотентная инициализация OTel для процесса."""
|
||||
global _INITIALIZED
|
||||
if _INITIALIZED:
|
||||
return
|
||||
|
||||
# Сначала — единый формат логов и фильтр trace_id.
|
||||
install_log_format()
|
||||
|
||||
resource = _resource(service_name, service_version)
|
||||
trace.set_tracer_provider(_build_trace_provider(resource))
|
||||
metrics.set_meter_provider(_build_meter_provider(resource))
|
||||
logger_provider = _build_logger_provider(resource)
|
||||
set_logger_provider(logger_provider)
|
||||
|
||||
# OTel handler шлёт те же записи в Collector → Loki. Он тоже видит
|
||||
# trace_id из record, потому что span-контекст един.
|
||||
#
|
||||
# ВАЖНО: LoggingHandler.emit() формирует тело через self.format(record),
|
||||
# где self.formatter наследуется от logging.Handler. Без явного
|
||||
# formatter'а тело будет голым сообщением (msg % args) — без
|
||||
# trace_id=/span_id=. Это ломало поиск в Loki `|= "trace_id="`.
|
||||
# Поэтому задаём тот же формат и навешиваем TraceContextFilter
|
||||
# непосредственно на OTel-хэндлер: фильтр должен отработать ДО emit,
|
||||
# чтобы record.trace_id существовал на момент форматирования.
|
||||
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
otel_handler.addFilter(TraceContextFilter())
|
||||
otel_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||
logging.getLogger().addHandler(otel_handler)
|
||||
|
||||
_INITIALIZED = True
|
||||
logging.getLogger("telemetry").info(
|
||||
"event=otel_init service=%s instance_id=%s endpoint=%s",
|
||||
service_name, INSTANCE_ID, _endpoint(),
|
||||
)
|
||||
|
||||
|
||||
def tracer(name: str = "app"):
|
||||
return trace.get_tracer(name)
|
||||
|
||||
|
||||
def meter(name: str = "app"):
|
||||
return metrics.get_meter(name)
|
||||
@@ -0,0 +1,405 @@
|
||||
"""Worker lab5/lab6: обработка вложений из RabbitMQ с трейсингом.
|
||||
|
||||
- at-least-once, идемпотентно, retry через TTL-очередь, DLQ.
|
||||
- OTel: consumer span на каждый job, извлечение trace context из заголовков
|
||||
сообщения (W3C traceparent/tracestate), child spans на S3/DB операции.
|
||||
- Метрики: jobs_processed_total{outcome}, job_processing_duration_seconds.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pika
|
||||
from PIL import Image, ImageOps
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage import s3
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import (
|
||||
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||
publish_retry, publish_dlq,
|
||||
)
|
||||
from .telemetry import init_telemetry, meter
|
||||
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
log = logging.getLogger("worker")
|
||||
|
||||
PIPELINE_VERSION = 1
|
||||
LEASE_SECONDS = 60
|
||||
THUMB_SIZE = (256, 256)
|
||||
CROP_SIZE = (128, 128)
|
||||
OPT_SIZE = (1280, 1280)
|
||||
OPT_QUALITY = 82
|
||||
|
||||
_stop = False
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
# OTel инициализация — до первого сообщения
|
||||
init_telemetry("messenger-worker", "1.6.0")
|
||||
_tracer = trace.get_tracer("worker")
|
||||
_meter = meter("messenger-worker")
|
||||
_jobs_counter = _meter.create_counter(
|
||||
"jobs_processed_total", description="Jobs processed by outcome", unit="1",
|
||||
)
|
||||
# Явные границы бакетов в СЕКУНДАХ: job-обработка (decode + resize + 3×S3 PUT
|
||||
# + DB) обычно от десятков мс до единиц секунд. Дефолтные экспоненциальные
|
||||
# бакеты слишком грубы для p95/p99 на этой шкале.
|
||||
_JOB_DURATION_BUCKETS = [
|
||||
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5,
|
||||
0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 30.0,
|
||||
]
|
||||
_jobs_hist = _meter.create_histogram(
|
||||
"job_processing_duration_seconds",
|
||||
description="Job processing duration",
|
||||
unit="s",
|
||||
explicit_bucket_boundaries_advisory=_JOB_DURATION_BUCKETS,
|
||||
)
|
||||
|
||||
|
||||
# --- span helpers: дочерние операции S3/DB ---
|
||||
#
|
||||
# ВАЖНО: атрибуты, содержащие точку (`db.operation`, `aws.s3.key` и т.п.),
|
||||
# нельзя передавать как kwargs — Python-идентификатор с точкой невозможен.
|
||||
# Поэтому оба хелпера принимают dict атрибутов.
|
||||
|
||||
def _s3_span(name: str, attrs: dict):
|
||||
"""Context manager для S3-операции (CLIENT span внутри job.consume)."""
|
||||
return _tracer.start_as_current_span(
|
||||
name,
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={"messaging.system": "s3", **attrs},
|
||||
)
|
||||
|
||||
|
||||
def _db_span(name: str, attrs: dict):
|
||||
"""Context manager для DB-операции (CLIENT span внутри job.consume)."""
|
||||
return _tracer.start_as_current_span(
|
||||
name,
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={"db.system": "postgresql", **attrs},
|
||||
)
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
global _stop
|
||||
log.info("event=sigterm_received signal=%s", signum)
|
||||
_stop = True
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
from datetime import datetime, timezone
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGBA")
|
||||
bg = Image.new("RGB", img.size, (255, 255, 255))
|
||||
bg.paste(img, mask=img.split()[-1])
|
||||
return bg
|
||||
if img.mode != "RGB":
|
||||
return img.convert("RGB")
|
||||
return img
|
||||
|
||||
|
||||
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
w, h = img.size
|
||||
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
nh = max(1, int(h * scale))
|
||||
thumb = img.resize((nw, nh), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
thumb.save(buf, format="JPEG", quality=88, optimize=True)
|
||||
return thumb, buf.getvalue()
|
||||
|
||||
|
||||
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
w, h = img.size
|
||||
side = min(w, h)
|
||||
left = (w - side) // 2
|
||||
top = (h - side) // 2
|
||||
sq = img.crop((left, top, left + side, top + side))
|
||||
crop = sq.resize(CROP_SIZE, Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
crop.save(buf, format="JPEG", quality=88, optimize=True)
|
||||
return crop, buf.getvalue()
|
||||
|
||||
|
||||
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
w, h = img.size
|
||||
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
nh = max(1, int(h * scale))
|
||||
opt = img.resize((nw, nh), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
opt.save(buf, format="WEBP", quality=OPT_QUALITY, method=4)
|
||||
return opt, buf.getvalue()
|
||||
|
||||
|
||||
def _sha256(data: bytes) -> str:
|
||||
import hashlib
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _s3_put_variant(chat_id, att_id, name: str, data: bytes, ctype: str) -> str:
|
||||
"""Общий путь: S3 PUT варианта внутри CLIENT span."""
|
||||
key = s3.variant_key(chat_id, att_id, name)
|
||||
with _s3_span("s3.put_object", {
|
||||
"aws.s3.key": key,
|
||||
"s3.operation": "put_object",
|
||||
"s3.variant": name,
|
||||
"s3.content_type": ctype,
|
||||
"s3.size_bytes": len(data),
|
||||
}):
|
||||
s3.put_bytes(key, data, ctype)
|
||||
return key
|
||||
|
||||
|
||||
def process_job(payload: dict) -> None:
|
||||
"""Обработка одного job. Идемпотентна через finalize_ready.
|
||||
|
||||
Внутри активного job.consume (CONSUMER) span создаются дочерние CLIENT
|
||||
spans для S3 и DB, чтобы разложить задержку обработки по зависимостям.
|
||||
"""
|
||||
attachment_id = payload["attachment_id"]
|
||||
pipeline_version = payload.get("pipeline_version", 1)
|
||||
job_id = payload["job_id"]
|
||||
|
||||
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||
job_id, attachment_id, payload.get("attempt", 1))
|
||||
|
||||
with _db_span("db.claim_processing", {
|
||||
"db.operation": "UPDATE",
|
||||
"attachment_id": str(attachment_id),
|
||||
}):
|
||||
claimed = storage.claim_processing(attachment_id, LEASE_SECONDS)
|
||||
if not claimed:
|
||||
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||
return
|
||||
att, staging_key = pair
|
||||
if att.status == "ready":
|
||||
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
try:
|
||||
with _s3_span("s3.get_object", {
|
||||
"aws.s3.key": staging_key,
|
||||
"s3.operation": "get_object",
|
||||
"s3.variant": "staging",
|
||||
}):
|
||||
raw, ctype = s3.get_object(staging_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise RuntimeError("staging_unavailable") from exc
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(raw))
|
||||
img.load()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
with _db_span("db.finalize_failed", {
|
||||
"db.operation": "UPDATE",
|
||||
"error_code": "invalid_image",
|
||||
}):
|
||||
storage.finalize_failed(attachment_id, "invalid_image")
|
||||
log.warning("event=invalid_image attachment_id=%s type=%s",
|
||||
attachment_id, type(exc).__name__)
|
||||
return
|
||||
|
||||
img_rgb = _to_rgb_white(img)
|
||||
|
||||
# Финал: S3 PUT оригинала
|
||||
final_key = s3.original_key(att.chat_id, att.id)
|
||||
with _s3_span("s3.put_object", {
|
||||
"aws.s3.key": final_key,
|
||||
"s3.operation": "put_object",
|
||||
"s3.variant": "original",
|
||||
"s3.content_type": att.content_type,
|
||||
"s3.size_bytes": len(raw),
|
||||
}):
|
||||
s3.put_bytes(final_key, raw, att.content_type)
|
||||
|
||||
variants = [{
|
||||
"name": "original",
|
||||
"object_key": final_key,
|
||||
"content_type": att.content_type,
|
||||
"size_bytes": len(raw),
|
||||
"width": img.width,
|
||||
"height": img.height,
|
||||
"sha256": _sha256(raw),
|
||||
}]
|
||||
|
||||
# Thumbnail
|
||||
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||
thumb_key = _s3_put_variant(att.chat_id, att.id, "thumbnail", thumb_bytes, "image/jpeg")
|
||||
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||
variants.append({
|
||||
"name": "thumbnail", "object_key": thumb_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(thumb_bytes),
|
||||
"width": tw, "height": th, "sha256": _sha256(thumb_bytes),
|
||||
})
|
||||
|
||||
# Crop
|
||||
_, crop_bytes = _make_crop(img_rgb)
|
||||
crop_key = _s3_put_variant(att.chat_id, att.id, "crop", crop_bytes, "image/jpeg")
|
||||
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||
variants.append({
|
||||
"name": "crop", "object_key": crop_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(crop_bytes),
|
||||
"width": cw, "height": ch, "sha256": _sha256(crop_bytes),
|
||||
})
|
||||
|
||||
# Optimized
|
||||
_, opt_bytes = _make_optimized(img_rgb)
|
||||
opt_key = _s3_put_variant(att.chat_id, att.id, "optimized", opt_bytes, "image/webp")
|
||||
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||
variants.append({
|
||||
"name": "optimized", "object_key": opt_key,
|
||||
"content_type": "image/webp", "size_bytes": len(opt_bytes),
|
||||
"width": ow, "height": oh, "sha256": _sha256(opt_bytes),
|
||||
})
|
||||
|
||||
with _db_span("db.finalize_ready", {
|
||||
"db.operation": "UPDATE",
|
||||
"pipeline_version": pipeline_version,
|
||||
"variants_count": len(variants),
|
||||
}):
|
||||
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||
|
||||
# Cleanup staging — best-effort, не критичен для результата.
|
||||
try:
|
||||
with _s3_span("s3.delete_object", {
|
||||
"aws.s3.key": staging_key,
|
||||
"s3.operation": "delete_object",
|
||||
"s3.variant": "staging",
|
||||
}):
|
||||
s3.delete_object(staging_key)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
log.info("event=job_ready attachment_id=%s job_id=%s variants=%d",
|
||||
attachment_id, job_id, len(variants))
|
||||
|
||||
|
||||
def _extract_trace_context(properties) -> otel_context.Context:
|
||||
"""Извлекает W3C traceparent/tracestate из headers. Ошибка → пустой контекст."""
|
||||
try:
|
||||
headers = dict(properties.headers or {})
|
||||
carrier = {
|
||||
k.lower(): str(v)
|
||||
for k, v in headers.items()
|
||||
if k.lower() in ("traceparent", "tracestate")
|
||||
}
|
||||
if not carrier:
|
||||
return otel_context.Context()
|
||||
return _propagator.extract(carrier=carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=trace_extract_failed type=%s", type(exc).__name__)
|
||||
return otel_context.Context()
|
||||
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно. Оборачивает обработку в CONSUMER span."""
|
||||
parent_ctx = _extract_trace_context(properties)
|
||||
started = time.monotonic()
|
||||
with _tracer.start_as_current_span(
|
||||
"job.consume", context=parent_ctx, kind=SpanKind.CONSUMER,
|
||||
attributes={"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE},
|
||||
) as span:
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
log.error("event=invalid_job_json")
|
||||
_jobs_counter.add(1, {"job.type": "unknown", "outcome": "invalid"})
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
span.set_attribute("job.id", str(payload.get("job_id", "")))
|
||||
span.set_attribute("job.type", str(payload.get("type", "unknown")))
|
||||
span.set_attribute("job.attempt", retry_count + 1)
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
duration = time.monotonic() - started
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
duration = time.monotonic() - started
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
try:
|
||||
with _db_span("db.finalize_failed", {
|
||||
"db.operation": "UPDATE",
|
||||
"error_code": "retry_exhausted",
|
||||
}):
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception:
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
log.info("event=worker_start queue=%s max_attempts=%s", QUEUE, MAX_ATTEMPTS)
|
||||
|
||||
while not _stop:
|
||||
try:
|
||||
conn = connect()
|
||||
ch = conn.channel()
|
||||
setup_topology(ch)
|
||||
ch.basic_qos(prefetch_count=1)
|
||||
ch.basic_consume(queue=QUEUE, on_message_callback=_on_message)
|
||||
log.info("event=consumer_started")
|
||||
|
||||
while not _stop and conn.is_open:
|
||||
conn.process_data_events(time_limit=1)
|
||||
|
||||
ch.stop_consuming()
|
||||
conn.close()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=worker_loop_error type=%s", type(exc).__name__)
|
||||
time.sleep(3)
|
||||
|
||||
close_pool()
|
||||
log.info("event=worker_stop")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user