Files
mtusi2026lab7/app/broker.py
T
2026-11-27 23:05:20 +03:00

123 lines
4.1 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 объявляется инфраструктурой (infra/rabbitmq/definitions.json) при
старте RabbitMQ, а не приложением: приложению не нужны права на declare.
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 pika.credentials import ExternalCredentials
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=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 connect():
"""Новое соединение TLS+EXTERNAL (worker использует его для consume)."""
return _connect()
def get_channel():
"""Один канал на процесс; topology объявлена инфраструктурой."""
global _channel
if _channel is None or _channel.is_closed:
with _lock:
if _channel is None or _channel.is_closed:
_channel = _connect().channel()
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():
"""Broker доступен по TLS+EXTERNAL и topology на месте (passive declare)."""
conn = _connect()
try:
conn.channel().queue_declare(QUEUE, passive=True)
finally:
conn.close()
def wait_ready(timeout=30):
import time
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
declare_only()
return True
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