Refactor DB and RMQ handlers: add connection pool lifecycle, remove TLS for RMQ, switch to lifespan events in FastAPI, ensure safe startup/shutdown.

This commit is contained in:
florian committed 2025-10-08 17:41:03 +02:00
1 parent a211bd3156
commit 482a90ae7b
3 files changed
+75 -33

No files matched your search

+35 -24
View File
@@ -1,7 +1,6 @@
import pika
from typing import Dict
from secret_handler import return_credentials
import ssl
import json
import time
import sys
@@ -16,15 +15,12 @@ rmq_exchange = os.getenv("BACKEND_API_INTERNAL_RMQ_EXCHANGE","app_notifications"
MAX_RETRIES = 5
RETRY_DELAY = 5
def send_message_to_rmq(user_id: int, message: Dict):
def create_connection():
credentials = pika.PlainCredentials(username=rmq_username, password=rmq_password)
context = ssl.create_default_context()
context.check_hostname = False
ssl_options = pika.SSLOptions(context)
conn_params = pika.ConnectionParameters(
host=rmq_host,
port=5671,
ssl_options=ssl_options,
port=5672,
credentials=credentials,
virtual_host=rmq_vhost
)
@@ -32,22 +28,8 @@ def send_message_to_rmq(user_id: int, message: Dict):
for attempt in range(1, MAX_RETRIES + 1):
try:
connection = pika.BlockingConnection(conn_params)
channel = connection.channel()
channel.exchange_declare(exchange=rmq_exchange, exchange_type="topic", durable=True)
channel.confirm_delivery()
channel.basic_publish(
exchange=rmq_exchange,
routing_key=f"notify.user.{user_id}",
body=json.dumps(message),
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=2
),
mandatory=True
)
connection.close()
return
print("[RMQ] Connection established.")
return connection
except Exception as e:
print(f"[RMQ] Attempt {attempt} failed: {e}")
if attempt < MAX_RETRIES:
@@ -56,5 +38,34 @@ def send_message_to_rmq(user_id: int, message: Dict):
print("[RMQ] Failed to connect after maximum retries — exiting.")
sys.exit(1)
def send_message_to_rmq(connection, user_id: int, message: Dict):
if not connection or not connection.is_open:
raise RuntimeError("RabbitMQ connection is not open")
channel = connection.channel()
channel.exchange_declare(exchange=rmq_exchange, exchange_type="topic", durable=True)
channel.confirm_delivery()
channel.basic_publish(
exchange=rmq_exchange,
routing_key=f"notify.user.{user_id}",
body=json.dumps(message),
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=2
),
mandatory=True
)
def close_connection(connection):
if connection and connection.is_open:
connection.close()
print("[RMQ] Connection closed.")
if __name__ == "__main__":
send_message_to_rmq(1, {"type": "notification", "content": "Vault TLS cert reloaded successfully."})
conn = create_connection()
send_message_to_rmq(conn, 1, {"type": "notification", "content": "Vault TLS cert reloaded successfully."})
close_connection(conn)