абораторная 5: брокер, worker, outbox, варианты изображений, тесты отказов (оценка 4)

This commit is contained in:
kalibr456
2026-10-24 16:03:46 +03:00
parent 276dbdad8a
commit 9863bb0505
112 changed files with 10533 additions and 26 deletions
+105
View File
@@ -0,0 +1,105 @@
"""RabbitMQ: подключение, проверка топологии, публикация с publisher confirms.
Топология объявлена декларативно в definitions (secrets/rabbitmq_definitions.json, генерирует
scripts/init_secrets.py) и загружается брокером при каждом старте. У сервисов нет права configure:
они только проверяют её пассивным declare и не могут создать/удалить очередь.
exchange attachments (direct, durable)
--attachment.process.v1--> queue attachments.process.v1 (quorum, durable)
x-delivery-limit=20, dead-letter -> attachments.dlx (стратегия at-least-once),
x-max-length=100000 + x-overflow=reject-publish (переполнение -> nack издателю, не потеря)
exchange attachments.dlx (direct, durable)
--attachment.process.v1.dlq--> queue attachments.process.v1.dlq (classic, durable: просмотр в ops.py
через basic_get + nack не расходует delivery-limit)
Сообщения persistent (delivery_mode=2). Quorum queue пишет их в журнал Raft на диск (fsync) до
подтверждения издателю; при рестарте брокера с volume сообщения и неподтверждённые доставки сохраняются.
"""
import json
import logging
import pika
from pika.exceptions import AMQPError
import pipeline
import settings
log = logging.getLogger("messenger.broker")
logging.getLogger("pika").setLevel(logging.WARNING) # pika пишет INFO на каждое соединение/канал
BrokerError = (AMQPError, OSError)
def parameters(url: str | None = None) -> pika.URLParameters:
params = pika.URLParameters(url or settings.BROKER_URL)
params.heartbeat = settings.BROKER_HEARTBEAT_SECONDS
params.blocked_connection_timeout = 30 # брокер в memory/disk alarm блокирует издателя: не ждать вечно
params.socket_timeout = 5
params.connection_attempts = 1
params.client_properties = {"connection_name": settings.INSTANCE_ID}
return params
def connect(url: str | None = None) -> pika.BlockingConnection:
return pika.BlockingConnection(parameters(url))
def check_topology(channel) -> dict:
"""Пассивная проверка: exchange и очереди существуют. Возвращает число сообщений в очередях."""
channel.exchange_declare(pipeline.EXCHANGE, passive=True)
main = channel.queue_declare(pipeline.QUEUE, passive=True).method
dlq = channel.queue_declare(pipeline.DLQ, passive=True).method
return {"queue": main.message_count, "consumers": main.consumer_count, "dlq": dlq.message_count}
def properties(message: dict) -> pika.BasicProperties:
headers = {}
if "traceparent" in message:
headers["traceparent"] = message["traceparent"] # тот же carrier и в native headers
return pika.BasicProperties(
delivery_mode=pika.DeliveryMode.Persistent,
content_type="application/json",
message_id=f"{message['job_id']}:{message['attempt']}",
type=message["type"],
headers=headers or None,
)
class Publisher:
"""Канал в режиме confirm: basic_publish возвращает управление только после ack брокера.
mandatory=True: если сообщение некуда положить (нет привязки), брокер вернёт его -> UnroutableError.
Nack (например, очередь переполнена и x-overflow=reject-publish) -> NackError. В обоих случаях
строка outbox остаётся неопубликованной и будет отправлена позже.
"""
def __init__(self):
self.connection = None
self.channel = None
def open(self):
if self.channel is None or self.channel.is_closed or self.connection.is_closed:
self.close()
self.connection = connect()
self.channel = self.connection.channel()
self.channel.confirm_delivery()
check_topology(self.channel)
log.info("connected to broker, publisher confirms enabled")
return self.channel
def publish(self, message: dict, exchange: str = pipeline.EXCHANGE, routing_key: str = pipeline.ROUTING_KEY):
body = json.dumps(message, separators=(",", ":")).encode("utf-8")
self.open().basic_publish(exchange, routing_key, body, properties(message), mandatory=True)
def pump(self):
if self.connection is not None and self.connection.is_open:
self.connection.process_data_events(time_limit=0) # heartbeat в паузах
def close(self):
try:
if self.connection is not None and self.connection.is_open:
self.connection.close()
except BrokerError:
pass
self.connection = None
self.channel = None