|
| 1 | +import asyncio |
| 2 | +import textwrap |
| 3 | +import typing |
| 4 | + |
| 5 | +from ._config import AppConfig |
| 6 | +from ._connection_info import ConnectionInfo |
| 7 | +from ._process import kill_process_by_port |
| 8 | +from ..functions.ext.asgi import Application |
| 9 | + |
| 10 | +if typing.TYPE_CHECKING: |
| 11 | + from ._uvicorn_util import AwaitableUvicornServer |
| 12 | + |
| 13 | +# Keep track of currently running server |
| 14 | +_running_server: 'typing.Optional[AwaitableUvicornServer]' = None |
| 15 | + |
| 16 | + |
| 17 | +async def run_udf_app( |
| 18 | + app: Application, |
| 19 | + log_level: str = 'error', |
| 20 | + kill_existing_app_server: bool = True, |
| 21 | +) -> ConnectionInfo: |
| 22 | + global _running_server |
| 23 | + from ._uvicorn_util import AwaitableUvicornServer |
| 24 | + |
| 25 | + try: |
| 26 | + import uvicorn |
| 27 | + except ImportError: |
| 28 | + raise ImportError('package uvicorn is required to run python udfs') |
| 29 | + |
| 30 | + app_config = AppConfig.from_env() |
| 31 | + |
| 32 | + if kill_existing_app_server: |
| 33 | + # Shutdown the server gracefully if it was started by us. |
| 34 | + # Since the uvicorn server doesn't start a new subprocess |
| 35 | + # killing the process would result in kernel dying. |
| 36 | + if _running_server is not None: |
| 37 | + await _running_server.shutdown() |
| 38 | + _running_server = None |
| 39 | + |
| 40 | + # Kill if any other process is occupying the port |
| 41 | + kill_process_by_port(app_config.listen_port) |
| 42 | + |
| 43 | + app.root_path = app_config.base_path |
| 44 | + |
| 45 | + config = uvicorn.Config( |
| 46 | + app, |
| 47 | + host='0.0.0.0', |
| 48 | + port=app_config.listen_port, |
| 49 | + log_level=log_level, |
| 50 | + ) |
| 51 | + _running_server = AwaitableUvicornServer(config) |
| 52 | + |
| 53 | + app.register_functions(replace=True) |
| 54 | + asyncio.create_task(_running_server.serve()) |
| 55 | + await _running_server.wait_for_startup() |
| 56 | + |
| 57 | + connection_info = ConnectionInfo(app_config.base_url, app_config.token) |
| 58 | + |
| 59 | + print( |
| 60 | + 'Following Python UDFs are available: ', app.get_function_info() |
| 61 | + ) |
| 62 | + |
| 63 | + return connection_info |
0 commit comments