Files
mtusi2026lab5/src/broker.py
T

65 lines
2.1 KiB
Python

import json
import logging
import os
import pika
from .config import secret
from .errors import ApiError
QUEUE = 'attachment.process.v1'
def connect():
parameters = pika.URLParameters(secret('BROKER_URL_FILE'))
parameters.heartbeat = 10
parameters.socket_timeout = 2
parameters.stack_timeout = 8
parameters.blocked_connection_timeout = 5
parameters.connection_attempts = 1
logging.getLogger('pika').setLevel(logging.CRITICAL)
return pika.BlockingConnection(parameters)
def publish(job):
connection = None
try:
connection = connect()
channel = connection.channel()
channel.queue_declare(queue=QUEUE, durable=True)
channel.confirm_delivery()
channel.basic_publish(exchange='', routing_key=QUEUE, mandatory=True,
body=json.dumps(job, separators=(',', ':')).encode(),
properties=pika.BasicProperties(delivery_mode=2, content_type='application/json',
message_id=job['job_id']))
except (pika.exceptions.AMQPError, OSError):
raise ApiError(503, 'unavailable', 'Очередь недоступна') from None
finally:
if connection and connection.is_open:
try:
connection.close()
except (pika.exceptions.AMQPError, OSError):
pass
def ready():
connection = None
try:
connection = connect()
connection.channel().queue_declare(queue=QUEUE, durable=True)
except (pika.exceptions.AMQPError, OSError):
raise ApiError(503, 'unavailable', 'Очередь недоступна') from None
finally:
if connection and connection.is_open:
try:
connection.close()
except (pika.exceptions.AMQPError, OSError):
pass
def envelope(row, attempt=1):
return {'schema_version': 1, 'job_id': str(row['id']), 'type': QUEUE,
'attachment_id': str(row['attachment_id']), 'pipeline_version': 1,
'attempt': attempt, 'created_at': row['created_at'].isoformat().replace('+00:00', 'Z')}