Skip to content

Refactor: Centralize RabbitMQ connection logic into shared utility #3

@allipry

Description

@allipry

Problem

RabbitMQ connection setup is duplicated in 4+ locations:

  1. opentakserver/blueprints/scheduled_jobs.py - _get_rabbitmq_connection() helper
  2. opentakserver/controllers/rabbitmq_client.py - inline setup
  3. opentakserver/cot_parser/cot_parser.py - inline setup
  4. opentakserver/eud_handler/client_controller.py - inline setup

Each location has nearly identical code:

rmq_credentials = pika.PlainCredentials(
    app.config.get("OTS_RABBITMQ_USERNAME", "guest"),
    app.config.get("OTS_RABBITMQ_PASSWORD", "guest")
)
rmq_params = pika.ConnectionParameters(
    host=app.config.get("OTS_RABBITMQ_SERVER_ADDRESS", "localhost"),
    port=int(app.config.get("OTS_RABBITMQ_PORT", 5672)),
    virtual_host=app.config.get("OTS_RABBITMQ_VHOST", "/"),
    credentials=rmq_credentials
)

Solution

Create a shared utility module:

# opentakserver/utils/rabbitmq.py

import pika
from urllib.parse import quote

def get_rabbitmq_params(config):
    """Build pika ConnectionParameters from Flask config."""
    credentials = pika.PlainCredentials(
        config.get("OTS_RABBITMQ_USERNAME", "guest"),
        config.get("OTS_RABBITMQ_PASSWORD", "guest")
    )
    return pika.ConnectionParameters(
        host=config.get("OTS_RABBITMQ_SERVER_ADDRESS", "localhost"),
        port=int(config.get("OTS_RABBITMQ_PORT", 5672)),
        virtual_host=config.get("OTS_RABBITMQ_VHOST", "/"),
        credentials=credentials
    )

def get_rabbitmq_url(config):
    """Build AMQP URL string from Flask config."""
    user = quote(config.get("OTS_RABBITMQ_USERNAME", "guest"), safe='')
    password = quote(config.get("OTS_RABBITMQ_PASSWORD", "guest"), safe='')
    host = config.get("OTS_RABBITMQ_SERVER_ADDRESS", "localhost")
    port = config.get("OTS_RABBITMQ_PORT", 5672)
    vhost = config.get("OTS_RABBITMQ_VHOST", "/")
    return f"amqp://{user}:{password}@{host}:{port}/{vhost}"

Benefits

  • Single source of truth for RabbitMQ configuration
  • Easier to maintain and update
  • Consistent behavior across all connection points
  • Easier to add features like connection pooling or retry logic

Related

Identified during code review of PR #1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions