|
1 | 1 | """
|
2 | 2 | Library level functions and states.
|
3 | 3 | """
|
4 |
| -import json |
5 | 4 | import os
|
6 | 5 | import sys
|
7 |
| -from typing import Callable, Self |
| 6 | +import functools |
| 7 | +import inspect |
| 8 | +import asyncio |
| 9 | +from typing import Callable, Self, Any |
8 | 10 | from dataclasses import dataclass
|
9 | 11 |
|
10 | 12 | from . import _engine
|
@@ -78,20 +80,40 @@ def main_fn(
|
78 | 80 |
|
79 | 81 | If the settings are not provided, they are loaded from the environment variables.
|
80 | 82 | """
|
81 |
| - def _main_wrapper(fn: Callable) -> Callable: |
82 | 83 |
|
83 |
| - def _inner(*args, **kwargs): |
84 |
| - effective_settings = settings or Settings.from_env() |
85 |
| - init(effective_settings) |
86 |
| - try: |
87 |
| - if len(sys.argv) > 1 and sys.argv[1] == cocoindex_cmd: |
88 |
| - return cli.cli.main(sys.argv[2:], prog_name=f"{sys.argv[0]} {sys.argv[1]}") |
89 |
| - else: |
90 |
| - return fn(*args, **kwargs) |
91 |
| - finally: |
92 |
| - stop() |
| 84 | + def _pre_init() -> None: |
| 85 | + effective_settings = settings or Settings.from_env() |
| 86 | + init(effective_settings) |
| 87 | + |
| 88 | + def _should_run_cli() -> bool: |
| 89 | + return len(sys.argv) > 1 and sys.argv[1] == cocoindex_cmd |
93 | 90 |
|
94 |
| - _inner.__name__ = fn.__name__ |
95 |
| - return _inner |
| 91 | + def _run_cli(): |
| 92 | + return cli.cli.main(sys.argv[2:], prog_name=f"{sys.argv[0]} {sys.argv[1]}") |
| 93 | + |
| 94 | + def _main_wrapper(fn: Callable) -> Callable: |
| 95 | + if inspect.iscoroutinefunction(fn): |
| 96 | + @functools.wraps(fn) |
| 97 | + async def _inner(*args, **kwargs): |
| 98 | + _pre_init() |
| 99 | + try: |
| 100 | + if _should_run_cli(): |
| 101 | + # Schedule to a separate thread as it invokes nested event loop. |
| 102 | + return await asyncio.to_thread(_run_cli) |
| 103 | + return await fn(*args, **kwargs) |
| 104 | + finally: |
| 105 | + stop() |
| 106 | + return _inner |
| 107 | + else: |
| 108 | + @functools.wraps(fn) |
| 109 | + def _inner(*args, **kwargs): |
| 110 | + _pre_init() |
| 111 | + try: |
| 112 | + if _should_run_cli(): |
| 113 | + return _run_cli() |
| 114 | + return fn(*args, **kwargs) |
| 115 | + finally: |
| 116 | + stop() |
| 117 | + return _inner |
96 | 118 |
|
97 | 119 | return _main_wrapper
|
0 commit comments