|
| 1 | +import logging |
| 2 | +from typing import cast |
| 3 | + |
| 4 | +from fastapi import FastAPI |
| 5 | +from servicelib.logging_utils import log_context |
| 6 | +from servicelib.rabbitmq import ( |
| 7 | + RabbitMQClient, |
| 8 | + RabbitMQRPCClient, |
| 9 | + wait_till_rabbitmq_responsive, |
| 10 | +) |
| 11 | +from settings_library.rabbit import RabbitSettings |
| 12 | + |
| 13 | +from ..exceptions.errors import ConfigurationError |
| 14 | + |
| 15 | +_logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def setup(app: FastAPI) -> None: |
| 19 | + async def on_startup() -> None: |
| 20 | + with log_context( |
| 21 | + _logger, |
| 22 | + logging.INFO, |
| 23 | + msg="Storage startup Rabbitmq", |
| 24 | + ): |
| 25 | + app.state.rabbitmq_client = None |
| 26 | + rabbit_settings: RabbitSettings | None = app.state.settings.STORAGE_RABBITMQ |
| 27 | + if not rabbit_settings: |
| 28 | + raise ConfigurationError( |
| 29 | + msg="RabbitMQ client is de-activated in the settings" |
| 30 | + ) |
| 31 | + await wait_till_rabbitmq_responsive(rabbit_settings.dsn) |
| 32 | + app.state.rabbitmq_client = RabbitMQClient( |
| 33 | + client_name="storage", settings=rabbit_settings |
| 34 | + ) |
| 35 | + app.state.rabbitmq_rpc_server = await RabbitMQRPCClient.create( |
| 36 | + client_name="storage_rpc_server", settings=rabbit_settings |
| 37 | + ) |
| 38 | + |
| 39 | + async def on_shutdown() -> None: |
| 40 | + with log_context( |
| 41 | + _logger, |
| 42 | + logging.INFO, |
| 43 | + msg="Storage shutdown Rabbitmq", |
| 44 | + ): |
| 45 | + if app.state.rabbitmq_client: |
| 46 | + await app.state.rabbitmq_client.close() |
| 47 | + if app.state.rabbitmq_rpc_server: |
| 48 | + await app.state.rabbitmq_rpc_server.close() |
| 49 | + |
| 50 | + app.add_event_handler("startup", on_startup) |
| 51 | + app.add_event_handler("shutdown", on_shutdown) |
| 52 | + |
| 53 | + |
| 54 | +def get_rabbitmq_client(app: FastAPI) -> RabbitMQClient: |
| 55 | + if not app.state.rabbitmq_client: |
| 56 | + raise ConfigurationError( |
| 57 | + msg="RabbitMQ client is not available. Please check the configuration." |
| 58 | + ) |
| 59 | + return cast(RabbitMQClient, app.state.rabbitmq_client) |
| 60 | + |
| 61 | + |
| 62 | +def get_rabbitmq_rpc_server(app: FastAPI) -> RabbitMQRPCClient: |
| 63 | + assert app.state.rabbitmq_rpc_server # nosec |
| 64 | + return cast(RabbitMQRPCClient, app.state.rabbitmq_rpc_server) |
0 commit comments