Files
mtusi2026lab6/app/broker.py
alenchha 0638263029 ЛР 6 — БВТ2301 — Курлова — на 5 (трек 1 «Цена наблюдаемости»)
Перенесён минимум lab5 без изменения API и добавлена наблюдаемость:
- OTel SDK в API и worker: traces, metrics, logs по OTLP; W3C trace context
  API -> outbox -> RabbitMQ -> worker (producer/consumer spans, retry в той же трассе);
- OTel Collector (memory_limiter, scrub, batch, ограниченные очереди, профиль tail sampling),
  Prometheus, Loki, Tempo, Grafana с provisioning, dashboard и 6 alert rules с runbooks;
- проверки: наблюдаемость и приватность, инциденты A/B/C, насыщение worker,
  переполнение очереди exporter, эксперимент трека 1 (4 конфигурации x 3 прогона);
- CI job со сборкой и запуском стенда; REPORT.md с доказательствами в evidence/.
2026-11-11 09:24:27 +03:00

80 lines
3.1 KiB
Python

"""RabbitMQ topology and confirmed publishing (aio-pika).
Topology (declared idempotently by every publisher and consumer):
exchange attachments direct, durable
queue attachments.process quorum, durable, dead-letter -> attachments.dlx, x-delivery-limit
exchange attachments.dlx fanout, durable
queue attachments.dlq quorum, durable (poison / undeliverable messages for the operator)
Messages are persistent; the channel uses publisher confirms, so `publish` returns only after the broker
has taken responsibility for the message (written to the quorum log).
"""
import json
import logging
import aio_pika
from aio_pika import DeliveryMode, ExchangeType, Message
from app import config
log = logging.getLogger("messenger.broker")
ROUTING_KEY = "attachment.process.v1"
async def connect():
return await aio_pika.connect_robust(config.BROKER_URL, timeout=5, client_properties={"connection_name": config.INSTANCE_ID})
async def declare(channel):
dlx = await channel.declare_exchange(config.BROKER_DLX, ExchangeType.FANOUT, durable=True)
dlq = await channel.declare_queue(config.BROKER_DLQ, durable=True, arguments={"x-queue-type": "quorum"})
await dlq.bind(dlx)
exchange = await channel.declare_exchange(config.BROKER_EXCHANGE, ExchangeType.DIRECT, durable=True)
queue = await channel.declare_queue(
config.BROKER_QUEUE,
durable=True,
arguments={
"x-queue-type": "quorum",
"x-dead-letter-exchange": config.BROKER_DLX,
"x-delivery-limit": config.BROKER_DELIVERY_LIMIT,
},
)
await queue.bind(exchange, ROUTING_KEY)
return exchange, queue
class Publisher:
def __init__(self) -> None:
self.connection = None
self.channel = None
self.exchange = None
async def ensure(self) -> None:
if self.channel is not None and not self.channel.is_closed:
return
if self.connection is None or self.connection.is_closed:
self.connection = await connect()
self.channel = await self.connection.channel(publisher_confirms=True)
self.exchange, _ = await declare(self.channel)
async def publish(self, body: dict) -> None:
await self.ensure()
message = Message(
json.dumps(body, separators=(",", ":")).encode(),
content_type="application/json",
delivery_mode=DeliveryMode.PERSISTENT,
message_id=body["job_id"],
type=body["type"],
# Native AMQP headers duplicate the body carrier (same W3C values) for broker-side tooling.
headers={"attempt": body["attempt"], **{k: body[k] for k in ("traceparent", "tracestate") if k in body}},
)
# mandatory: an unroutable message is an error, not a silent drop; awaited confirm = broker ack.
await self.exchange.publish(message, routing_key=ROUTING_KEY, mandatory=True, timeout=5)
async def close(self) -> None:
try:
if self.connection is not None:
await self.connection.close()
except Exception:
pass
self.connection = self.channel = self.exchange = None