def app_init() -> FastAPI: logger.info("Initializing app") config.validate(logger) debug = config["DEBUG"] app = FastAPI( title="Audit Service", version=version("audit"), debug=debug, root_path=config["DOCS_URL_PREFIX"], ) app.add_middleware(ClientDisconnectMiddleware) app.async_client = httpx.AsyncClient() # Following will update logger level, propagate, and handlers get_logger("audit-service", log_level="debug" if debug == True else "info") logger.info("Initializing Arborist client") if os.environ.get("ARBORIST_URL"): app.arborist_client = ArboristClient( arborist_base_url=os.environ["ARBORIST_URL"], logger=logger, ) else: app.arborist_client = ArboristClient(logger=logger) db.init_app(app) load_modules(app) @app.on_event("startup") async def startup_event(): if (config["PULL_FROM_QUEUE"] and config["QUEUE_CONFIG"].get("type") == "aws_sqs"): loop = asyncio.get_running_loop() loop.create_task(pull_from_queue_loop()) loop.set_exception_handler(handle_exception) @app.on_event("shutdown") async def shutdown_event(): logger.info("Closing async client.") await app.async_client.aclose() logger.info("[Completed] Closing async client.") def handle_exception(loop, context): """ Whenever an exception occurs in the asyncio loop, the loop still continues to execute without crashing. Therefore, we implement a custom exception handler that will ensure that the loop is stopped upon an Exception. """ msg = context.get("exception", context.get("message")) logger.error(f"Caught exception: {msg}") for index, task in enumerate(asyncio.all_tasks()): task.cancel() logger.info("Closed all tasks") return app
def app_init() -> FastAPI: logger.info("Initializing app") config.validate() debug = config["DEBUG"] app = FastAPI( title="Requestor", version=version("requestor"), debug=debug, root_path=config["DOCS_URL_PREFIX"], ) app.add_middleware(ClientDisconnectMiddleware) app.async_client = httpx.AsyncClient() # Following will update logger level, propagate, and handlers get_logger("requestor", log_level="debug" if debug == True else "info") logger.info("Initializing Arborist client") custom_arborist_url = os.environ.get("ARBORIST_URL", config["ARBORIST_URL"]) if custom_arborist_url: app.arborist_client = ArboristClient( arborist_base_url=custom_arborist_url, authz_provider="requestor", logger=get_logger("requestor.gen3authz", log_level="debug"), ) else: app.arborist_client = ArboristClient( authz_provider="requestor", logger=get_logger("requestor.gen3authz", log_level="debug"), ) db.init_app(app) load_modules(app) @app.on_event("shutdown") async def shutdown_event(): logger.info("Closing async client.") await app.async_client.aclose() return app