Files
mtusi2026lab7/app/broker.py
T
eqktrinandO3 Agent Claude 23ac69428e ЛР7: перенести минимум lab6 в приложение (API, worker, OTel)
- бизнес-API без изменений контракта; транспорт теперь HTTPS за mTLS-relay
- retry задачи переопубликовывается через outbox (в lab6 задача после
  ошибки оставалась в queued навсегда); trace context сохраняется в
  outbox.headers, поэтому API -> broker -> worker остаётся одной трассой
- структурные JSON-логи: trace_id/span_id в теле строки (SDK игнорирует
  formatter, поэтому добавлен JsonLoggingHandler)
- закрыты дефекты lab6: закреплён uid datasource в dashboard, убрана
  зависимость от Valkey (сессии и rate limit - в PostgreSQL)
- метрики/логи/трассы уходят в Collector по OTLP с клиентским сертификатом

Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
2026-11-27 19:58:21 +03:00

125 lines
4.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""RabbitMQ: обязательный TLS + EXTERNAL-аутентификация по клиентскому сертификату.
Identity = CN сертификата (messenger-api / messenger-worker). Права выданы
раздельно и ограничены topology лаборатории (см. infra/rabbitmq/init.sh).
Topology:
exchange: lab5 (direct, durable)
routing_key: attachment.process.v1 → queue attachment.process.v1 (durable)
DLX: lab5.dlx (direct)
routing_key: attachment.failed → queue attachment.failed (durable)
"""
import json
import logging
import ssl
import threading
import pika
from . import config
log = logging.getLogger("broker")
EXCHANGE = "lab5"
DLX = "lab5.dlx"
QUEUE = "attachment.process.v1"
FAILED_QUEUE = "attachment.failed"
_lock = threading.Lock()
_channel = None
def _ssl_context():
ctx = ssl.create_default_context(cafile=config.BROKER_CA)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain(config.BROKER_CERT, config.BROKER_KEY)
return ctx
def _connect():
# Внешний механизм EXTERNAL: пароля нет, identity берётся из сертификата.
# server_hostname включает проверку имени (SAN/CN) сервера.
return pika.BlockingConnection(pika.ConnectionParameters(
host=config.BROKER_HOST,
port=config.BROKER_PORT,
virtual_host=config.BROKER_VHOST,
credentials=pika.ExternalCredentials(),
ssl_options=pika.SSLOptions(_ssl_context(), server_hostname=config.BROKER_HOST),
heartbeat=30,
blocked_connection_timeout=30,
connection_attempts=1,
socket_timeout=5,
))
def get_channel():
"""Один канал на процесс; worker также использует для consume."""
global _channel
if _channel is None or _channel.is_closed:
with _lock:
if _channel is None or _channel.is_closed:
ch = _connect().channel()
ch.exchange_declare(EXCHANGE, exchange_type="direct", durable=True)
ch.exchange_declare(DLX, exchange_type="direct", durable=True)
ch.queue_declare(
QUEUE, durable=True,
arguments={"x-dead-letter-exchange": DLX,
"x-dead-letter-routing-key": "attachment.failed"})
ch.queue_declare(FAILED_QUEUE, durable=True)
ch.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE)
ch.queue_bind(FAILED_QUEUE, DLX, routing_key="attachment.failed")
_channel = ch
return _channel
def publish(job_payload, headers=None):
"""Publish с publisher confirm.
headers — сохранённый в outbox W3C-контекст создания задачи; если не задан,
инжектится контекст текущего span. Так API → broker → worker остаются в
одной трассе даже когда публикация происходит в фоновом outbox-цикле.
"""
from . import telemetry # noqa: PLC0415 - избегаем цикла импортов
ch = get_channel()
ch.confirm_delivery()
body = json.dumps(job_payload, separators=(",", ":")).encode("utf-8")
carrier = dict(headers or {})
if not carrier:
telemetry.inject_headers(carrier)
ch.basic_publish(
exchange=EXCHANGE,
routing_key=QUEUE,
body=body,
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=2,
message_id=job_payload["job_id"],
headers=carrier or None,
),
mandatory=True,
)
def declare_only():
get_channel()
def wait_ready(timeout=30):
import time
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
conn = _connect()
try:
conn.channel().queue_declare(QUEUE, passive=True)
return True
finally:
conn.close()
except Exception as exc: # noqa: BLE001 - readiness probe
last = exc
time.sleep(0.5)
log.warning("broker not ready: %s", type(last).__name__ if last else "timeout")
return False