|
| 1 | +# -- encoding: utf-8 -- |
| 2 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 3 | +# This file is a part of the ModelEngine Project. |
| 4 | +# Licensed under the MIT License. See License.txt in the project root for license information. |
| 5 | +# ====================================================================================================================== |
| 6 | +""" |
| 7 | +Async executor for Nacos operations. |
| 8 | +
|
| 9 | +This module provides an async executor for handling Nacos operations |
| 10 | +in a background thread with proper event loop management. |
| 11 | +""" |
| 12 | +import asyncio |
| 13 | +import atexit |
| 14 | +import threading |
| 15 | +from concurrent.futures import Future |
| 16 | + |
| 17 | +from v2.nacos import NacosNamingService, RegisterInstanceParam, ListInstanceParam, \ |
| 18 | + DeregisterInstanceParam, SubscribeServiceParam, ListServiceParam |
| 19 | + |
| 20 | +from fitframework.api.logging import plugin_logger |
| 21 | +from .config import build_nacos_config |
| 22 | + |
| 23 | + |
| 24 | +class AsyncExecutor: |
| 25 | + """Executor for handling asynchronous operations in a background thread.""" |
| 26 | + |
| 27 | + def __init__(self): |
| 28 | + self._loop = None |
| 29 | + self._thread = None |
| 30 | + self._started = False |
| 31 | + self._shutdown = False |
| 32 | + self._nacos_client = None |
| 33 | + self._init_complete = threading.Event() |
| 34 | + |
| 35 | + def start(self): |
| 36 | + """Start the background event loop thread.""" |
| 37 | + if self._started: |
| 38 | + return |
| 39 | + |
| 40 | + self._thread = threading.Thread( |
| 41 | + target=self._run_event_loop, |
| 42 | + daemon=True, |
| 43 | + name="NacosAsyncThread" |
| 44 | + ) |
| 45 | + self._thread.start() |
| 46 | + |
| 47 | + # Wait for initialization to complete |
| 48 | + if not self._init_complete.wait(timeout=10): # Max wait 10 seconds |
| 49 | + raise RuntimeError("Failed to initialize async executor within timeout") |
| 50 | + |
| 51 | + self._started = True |
| 52 | + |
| 53 | + def _run_event_loop(self): |
| 54 | + """Run the event loop in the background thread.""" |
| 55 | + try: |
| 56 | + self._loop = asyncio.new_event_loop() |
| 57 | + asyncio.set_event_loop(self._loop) |
| 58 | + |
| 59 | + # Create Nacos client in this event loop |
| 60 | + async def init_nacos_client(): |
| 61 | + try: |
| 62 | + config = build_nacos_config() |
| 63 | + self._nacos_client = await NacosNamingService.create_naming_service(config) |
| 64 | + plugin_logger.info("Nacos client initialized successfully") |
| 65 | + except Exception as e: |
| 66 | + plugin_logger.error(f"Failed to initialize Nacos client: {e}") |
| 67 | + raise |
| 68 | + finally: |
| 69 | + # Mark initialization complete |
| 70 | + self._init_complete.set() |
| 71 | + |
| 72 | + self._loop.run_until_complete(init_nacos_client()) |
| 73 | + |
| 74 | + # Run event loop until shutdown |
| 75 | + self._loop.run_forever() |
| 76 | + except Exception as e: |
| 77 | + plugin_logger.error(f"Error in async executor event loop: {e}") |
| 78 | + self._init_complete.set() # Set even on failure to avoid infinite wait |
| 79 | + finally: |
| 80 | + try: |
| 81 | + if self._nacos_client: |
| 82 | + # Cleanup Nacos client if needed |
| 83 | + pass |
| 84 | + if self._loop: |
| 85 | + self._loop.close() |
| 86 | + except Exception as e: |
| 87 | + plugin_logger.error(f"Error during cleanup: {e}") |
| 88 | + |
| 89 | + def run_coroutine(self, coro): |
| 90 | + """ |
| 91 | + Run a coroutine in the background event loop and return the result. |
| 92 | + |
| 93 | + Args: |
| 94 | + coro: The coroutine to run. |
| 95 | + |
| 96 | + Returns: |
| 97 | + The result of the coroutine. |
| 98 | + |
| 99 | + Raises: |
| 100 | + RuntimeError: If the executor is not properly initialized. |
| 101 | + """ |
| 102 | + if not self._started: |
| 103 | + self.start() |
| 104 | + |
| 105 | + if self._loop is None or self._nacos_client is None: |
| 106 | + raise RuntimeError("Async executor not properly initialized") |
| 107 | + |
| 108 | + # Create a Future to get the result |
| 109 | + result_future = Future() |
| 110 | + |
| 111 | + async def wrapped_coro(): |
| 112 | + try: |
| 113 | + result = await coro |
| 114 | + result_future.set_result(result) |
| 115 | + except Exception as e: |
| 116 | + result_future.set_exception(e) |
| 117 | + |
| 118 | + # Schedule the coroutine in the event loop |
| 119 | + self._loop.call_soon_threadsafe(asyncio.create_task, wrapped_coro()) |
| 120 | + |
| 121 | + # Wait for result |
| 122 | + return result_future.result(timeout=30) # 30 second timeout |
| 123 | + |
| 124 | + def get_nacos_client(self): |
| 125 | + """ |
| 126 | + Get the Nacos client instance. |
| 127 | + |
| 128 | + Returns: |
| 129 | + The Nacos client instance. |
| 130 | + """ |
| 131 | + if not self._started: |
| 132 | + self.start() |
| 133 | + return self._nacos_client |
| 134 | + |
| 135 | + def shutdown(self): |
| 136 | + """Shutdown the async executor.""" |
| 137 | + if self._loop and not self._loop.is_closed(): |
| 138 | + self._loop.call_soon_threadsafe(self._loop.stop) |
| 139 | + self._shutdown = True |
| 140 | + |
| 141 | + |
| 142 | +# Global async executor |
| 143 | +_async_executor = AsyncExecutor() |
| 144 | + |
| 145 | + |
| 146 | +def run_async_safely(coro): |
| 147 | + """ |
| 148 | + Run an async operation safely using the dedicated executor. |
| 149 | +
|
| 150 | + Args: |
| 151 | + coro: The coroutine to run. |
| 152 | +
|
| 153 | + Returns: |
| 154 | + The result of the coroutine. |
| 155 | + |
| 156 | + Raises: |
| 157 | + Exception: If the async operation fails. |
| 158 | + """ |
| 159 | + try: |
| 160 | + return _async_executor.run_coroutine(coro) |
| 161 | + except Exception as e: |
| 162 | + plugin_logger.error(f"Error running async operation: {e}") |
| 163 | + raise |
| 164 | + |
| 165 | + |
| 166 | +# Async wrapper functions |
| 167 | +async def call_list_instances(param: ListInstanceParam): |
| 168 | + """List instances.""" |
| 169 | + client = _async_executor.get_nacos_client() |
| 170 | + return await client.list_instances(param) |
| 171 | + |
| 172 | + |
| 173 | +async def call_deregister_instance(param: DeregisterInstanceParam) -> bool: |
| 174 | + """Deregister instance.""" |
| 175 | + client = _async_executor.get_nacos_client() |
| 176 | + return await client.deregister_instance(param) |
| 177 | + |
| 178 | + |
| 179 | +async def call_subscribe(param: SubscribeServiceParam) -> None: |
| 180 | + """Subscribe to service.""" |
| 181 | + client = _async_executor.get_nacos_client() |
| 182 | + await client.subscribe(param) |
| 183 | + |
| 184 | + |
| 185 | +async def call_unsubscribe(param: SubscribeServiceParam) -> None: |
| 186 | + """Unsubscribe from service.""" |
| 187 | + client = _async_executor.get_nacos_client() |
| 188 | + await client.unsubscribe(param) |
| 189 | + |
| 190 | + |
| 191 | +async def call_list_services(param: ListServiceParam): |
| 192 | + """List services.""" |
| 193 | + client = _async_executor.get_nacos_client() |
| 194 | + return await client.list_services(param) |
| 195 | + |
| 196 | + |
| 197 | +async def call_register_instance(param: RegisterInstanceParam) -> None: |
| 198 | + """Register instance.""" |
| 199 | + client = _async_executor.get_nacos_client() |
| 200 | + await client.register_instance(param) |
| 201 | + |
| 202 | + |
| 203 | +def _cleanup_async_executor(): |
| 204 | + """Cleanup the async executor.""" |
| 205 | + try: |
| 206 | + _async_executor.shutdown() |
| 207 | + except Exception as e: |
| 208 | + plugin_logger.error(f"Error during async executor cleanup: {e}") |
| 209 | + |
| 210 | + |
| 211 | +# Register cleanup function |
| 212 | +atexit.register(_cleanup_async_executor) |
0 commit comments