Files
mtusi2026lab7/queueing.py
T
Artem e7d7bbbe77
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР 7: Безопасность, mTLS и OpenBao
2026-12-05 18:23:13 +03:00

160 lines
5.3 KiB
Python

"""Durable RabbitMQ job publication shared by the API and worker."""
import json
import logging
import os
import ssl
from datetime import timezone
import pika
from opentelemetry.propagate import inject
JOB_QUEUE = "attachment.jobs.v1"
DEAD_LETTER_EXCHANGE = "attachment.jobs.dlx"
DEAD_LETTER_QUEUE = "attachment.jobs.dead"
DEAD_LETTER_ROUTING_KEY = "attachment.jobs.dead"
LOG = logging.getLogger("job-queue")
class BrokerUnavailable(Exception):
pass
def broker_url():
value = os.environ.get("BROKER_URL", "").strip()
if not value:
secret_file = os.environ.get("BROKER_URL_FILE", "").strip()
if secret_file:
try:
with open(secret_file, "r", encoding="utf-8") as secret:
value = secret.read().strip()
except OSError:
raise RuntimeError("BROKER_URL_FILE cannot be read") from None
if not value:
raise RuntimeError("BROKER_URL or BROKER_URL_FILE is required")
return value
def connection_parameters():
parameters = pika.URLParameters(broker_url())
parameters.connection_attempts = 1
parameters.socket_timeout = 4
parameters.stack_timeout = 8
parameters.blocked_connection_timeout = 8
parameters.heartbeat = 30
ca = os.environ.get("INTERNAL_CA_CERT", "").strip()
if broker_url().lower().startswith("amqps://") and ca:
context = ssl.create_default_context(cafile=ca)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
parameters.ssl_options = pika.SSLOptions(context, "broker")
return parameters
def declare_topology(channel):
channel.exchange_declare(
exchange=DEAD_LETTER_EXCHANGE,
exchange_type="direct",
durable=True,
)
channel.queue_declare(queue=DEAD_LETTER_QUEUE, durable=True)
channel.queue_bind(
queue=DEAD_LETTER_QUEUE,
exchange=DEAD_LETTER_EXCHANGE,
routing_key=DEAD_LETTER_ROUTING_KEY,
)
channel.queue_declare(
queue=JOB_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": DEAD_LETTER_EXCHANGE,
"x-dead-letter-routing-key": DEAD_LETTER_ROUTING_KEY,
},
)
def event_payload(job):
created_at = job["created_at"].astimezone(timezone.utc)
return {
"schema_version": 1,
"job_id": str(job["id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"],
"created_at": created_at.isoformat(timespec="microseconds").replace("+00:00", "Z"),
}
def publish_event(event):
inject(event)
body = json.dumps(event, separators=(",", ":"), sort_keys=True).encode("utf-8")
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
channel = connection.channel()
declare_topology(channel)
channel.confirm_delivery()
confirmed = channel.basic_publish(
exchange="",
routing_key=JOB_QUEUE,
body=body,
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=pika.DeliveryMode.Persistent,
message_id=event["job_id"],
type=event["type"],
),
mandatory=True,
)
if confirmed is False:
raise BrokerUnavailable("broker did not confirm the job")
except (pika.exceptions.AMQPError, OSError, TimeoutError, ValueError) as error:
raise BrokerUnavailable("broker did not durably accept the job") from error
finally:
if connection is not None and connection.is_open:
try:
connection.close()
except pika.exceptions.AMQPError as error:
LOG.warning("broker close failed error_type=%s", type(error).__name__)
def publish_pending_job(pool, job_id):
with pool.connection() as conn:
job = conn.execute(
"""SELECT id, attachment_id, pipeline_version, attempt, created_at,
published_attempt, status
FROM image_jobs
WHERE id = %s""",
(job_id,),
).fetchone()
if job is None or job["status"] != "queued":
return False
if job["published_attempt"] >= job["attempt"]:
return False
publish_event(event_payload(job))
with pool.connection() as conn:
conn.execute(
"""UPDATE image_jobs
SET published_attempt = GREATEST(published_attempt, %s),
updated_at = now()
WHERE id = %s AND status = 'queued' AND attempt = %s""",
(job["attempt"], job_id, job["attempt"]),
)
return True
def check_broker():
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
declare_topology(connection.channel())
except (pika.exceptions.AMQPError, OSError, TimeoutError, ValueError) as error:
raise BrokerUnavailable("broker is unavailable") from error
finally:
if connection is not None and connection.is_open:
try:
connection.close()
except pika.exceptions.AMQPError as error:
LOG.warning("broker close failed error_type=%s", type(error).__name__)